package com.itlong.cloud.controller.miniprogram;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itlong.cloud.POJO.DTO.app.*;
import com.itlong.cloud.POJO.DTO.common.PadFaceSyncDataDTO;
import com.itlong.cloud.POJO.DTO.common.WeChatVisitorMsgDTO;
import com.itlong.cloud.POJO.DTO.property.PadUserAuthPushDTO;
import com.itlong.cloud.POJO.PO.*;
import com.itlong.cloud.POJO.VO.MessageVO;
import com.itlong.cloud.POJO.VO.app.*;
import com.itlong.cloud.POJO.VO.miniprogram.MiniProgramMyEquipListVO;
import com.itlong.cloud.POJO.VO.miniprogram.MiniProgramPassRoomListVO;
import com.itlong.cloud.POJO.VO.miniprogram.MiniProgramVisitorInfoVO;
import com.itlong.cloud.POJO.VO.operate.OperateAdImgVO;
import com.itlong.cloud.POJO.VO.operate.OperateFaceApplyInfoVO;
import com.itlong.cloud.POJO.VO.operate.OperateProjectDetailVO;
import com.itlong.cloud.POJO.VO.property.*;
import com.itlong.cloud.PlatformConstants;
import com.itlong.cloud.abstracts.BaseController;
import com.itlong.cloud.annotation.LoggerInfo;
import com.itlong.cloud.annotation.UnAuthAccessRequired;
import com.itlong.cloud.annotation.UnParamEncrypt;
import com.itlong.cloud.constants.LogDescConstant;
import com.itlong.cloud.constants.RabbitMQConstant;
import com.itlong.cloud.constants.RedisConstant;
import com.itlong.cloud.enumerate.*;
import com.itlong.cloud.enumerate.ecode.*;
import com.itlong.cloud.enumerate.ecode_en.BaseErrorCodeEnumEN;
import com.itlong.cloud.equip.app.IAppDevicePassRecordServiceClient;
import com.itlong.cloud.equip.app.IAppDeviceServiceClient;
import com.itlong.cloud.equip.app.IAppVisitorPassCodeRecordServiceClient;
import com.itlong.cloud.equip.miniprogram.IMiniProgramEquipServiceClient;
import com.itlong.cloud.equip.property.IPadFaceSyncDataServiceClient;
import com.itlong.cloud.iottp.IIotBaiduFaceServiceClient;
import com.itlong.cloud.iottp.IIotTpSmsServiceClient;
import com.itlong.cloud.iottp.IWeChatTemplateMsgServiceClient;
import com.itlong.cloud.noncore.operate.IOperateMiniProgramFunctionServiceClient;
import com.itlong.cloud.project.app.IAppProjectAddressServiceClient;
import com.itlong.cloud.project.app.IAppProjectServiceClient;
import com.itlong.cloud.project.operate.IOperateAdManageServiceClient;
import com.itlong.cloud.project.operate.IOperateFaceApplyServiceClient;
import com.itlong.cloud.project.operate.IOperateProjectServiceClient;
import com.itlong.cloud.project.property.IPropertyRoomInfoServiceClient;
import com.itlong.cloud.rabbitmq.config.MessageSender;
import com.itlong.cloud.service.RedisService;
import com.itlong.cloud.thrown.DataAccessException;
import com.itlong.cloud.user.app.IAppHomeServiceClient;
import com.itlong.cloud.user.app.IAppMineServiceClient;
import com.itlong.cloud.user.app.IAppRegisterServiceClient;
import com.itlong.cloud.user.miniprogram.IMiniProgramLoginServiceClient;
import com.itlong.cloud.user.property.IPropertyHouseHoldInfoServiceClient;
import com.itlong.cloud.user.property.IPropertyVisitorServiceClient;
import com.itlong.cloud.utils.date.DateUtil;
import com.itlong.cloud.utils.encrypt.Md5EncryptUtil;
import com.itlong.cloud.utils.encrypt.UserTokenUtil;
import com.itlong.cloud.utils.file.UploadFileUtil;
import com.itlong.cloud.utils.network.http.HttpProtocolUtil;
import com.itlong.cloud.utils.node.JsonUtil;
import com.itlong.cloud.utils.page.Page;
import com.itlong.cloud.utils.picture.VerifyCodeUtils;
import com.itlong.cloud.utils.random.LogicIdUtil;
import com.itlong.cloud.utils.words.NumberHandlerUtil;
import com.itlong.cloud.utils.words.StringHandlerUtil;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <desc>
 *     小程序我的控制器
 * </desc>
 *
 * @create  2018/11/19
 */
@RestController
@RequestMapping("/mine")
@RefreshScope
public class MiniprogramMineController extends BaseController{

    private static final Logger LOG = LoggerFactory.getLogger(MiniprogramMineController.class);

    @Value("${" + PlatformConstants.FILE_FTP_HOST + "}")
    public String FILE_FTP_HOST;
    @Value("${" + PlatformConstants.FILE_FTP_PORT + "}")
    public String FILE_FTP_PORT;
    @Value("${" + PlatformConstants.FILE_FTP_USERNAME + "}")
    public String FILE_FTP_USERNAME;
    @Value("${" + PlatformConstants.FILE_FTP_PASSWORD + "}")
    public String FILE_FTP_PASSWORD;
    @Value("${" + PlatformConstants.FILE_ACCESS_URL + "}")
    public String FILE_ACCESS_URL;

    //解析userId用
    @Value("${" + PlatformConstants.MINI_PROGRAM_USER_TOKEN_KEY + "}")
    public String MINI_PROGRAM_USER_TOKEN_KEY;

    //解密用
    @Value("${" + PlatformConstants.MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY + "}")
    public String MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY;

    @Value("${" + PlatformConstants.PROPERTY_OPERATE_MINI_CONTENT_AES_ENCRYPT_KEY + "}")
    String propertyOperateMiniContentAesEncryptKey;//物业,运营,小程序

    @Autowired
    IPropertyRoomInfoServiceClient iPropertyRoomInfoServiceClient;

    @Autowired
    private RedisService redisService;

    @Autowired
    private MessageSender messageSender;

    @Autowired
    IAppProjectServiceClient iAppProjectServiceClient;


    @Autowired
    IAppHomeServiceClient iAppHomeServiceClient;

    @Autowired
    IIotTpSmsServiceClient iIotTpSmsServiceClient;

    @Autowired
    IAppRegisterServiceClient iAppRegisterServiceClient;

    @Autowired
    IAppProjectAddressServiceClient iAppProjectAddressServiceClient;

    @Autowired
    IAppVisitorPassCodeRecordServiceClient iAppVisitorPassCodeRecordServiceClient;

    @Autowired
    IAppDevicePassRecordServiceClient iAppDevicePassRecordServiceClient;

    @Autowired
    IAppMineServiceClient iAppMineServiceClient;

    @Autowired
    IMiniProgramEquipServiceClient iMiniProgramEquipServiceClient;

    @Autowired
    IMiniProgramLoginServiceClient userCache;

    @Autowired
    IOperateProjectServiceClient iOperateProjectServiceClient;

    @Autowired
    IAppDeviceServiceClient iAppDeviceServiceClient;

    @Autowired
    IOperateFaceApplyServiceClient iOperateFaceApplyServiceClient;

    @Autowired
    IIotBaiduFaceServiceClient iIotBaiduFaceServiceClient;

    @Autowired
    IPadFaceSyncDataServiceClient iPadFaceSyncDataServiceClient;

    @Autowired
    IWeChatTemplateMsgServiceClient iWeChatTemplateMsgServiceClient;

    @Autowired
    IPropertyVisitorServiceClient iPropertyVisitorServiceClient;

    @Autowired
    IPropertyHouseHoldInfoServiceClient iPropertyHouseHoldInfoServiceClient;

    @Autowired
    IOperateAdManageServiceClient iOperateAdManageServiceClient;

    @Autowired
    IOperateMiniProgramFunctionServiceClient iOperateMiniProgramFunctionServiceClient;

    /**
     * <desc>
     *      根据城市名称获取城市id。
     * <desc/>
     *
     * @param
     * @return
     * @author Jiaqi.X
     * @createDate 2020/05/28
     */
    @RequestMapping(path = "/getCityId",method = RequestMethod.POST)
    @ResponseBody
    public Object getCityId(String city,String createTime, String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            city = request.getAttribute("city") == null ? null : request.getAttribute("city").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("city",city);
            params.put("createTime",createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            Map<String,Object> result = new HashMap<>();
            result.put("cityId",iAppProjectServiceClient.getCityIdByCityName(city));
            messageVO = new MessageVO(BaseErrorCodeEnumEN.SUCCESS.getErrorCode(),result);
        }catch (Exception e){
            throw new DataAccessException("【APP首页】根据城市名称获取城市id失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      查询房屋列表
     * </desc>
     *
     * @param token
     * @param projectId 项目编号
     * @return
     * @author Qiang.S
     * @createDate 2018/11/20
     */
    @RequestMapping(value = "/myRoomsInfoALL",method = RequestMethod.POST)
    @ResponseBody
    public Object myRoomsInfoALL(String token,String projectId, String createTime, String sign){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyRoomInfoServiceClient.myRoomsInfoALL(userId,projectId));
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的板块】查询全部房屋列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      查询业主房屋列表
     * </desc>
     *
     * @param token
     * @param projectId 项目编号
     * @return
     * @author Qiang.S
     * @createDate 2018/11/20
     */
    @RequestMapping(value = "/myRoomsInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object myRoomsInfo(String token,String projectId, String createTime, String sign){
        MessageVO messageVO;
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyRoomInfoServiceClient.myRoomsInfo(userId,projectId));
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的板块】查询业主房屋列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      小程序_我的版块根据项目编号、楼栋ID、单元ID、房间ID获取房间业主的电话号码
     * </desc>
     *
     * @param roomId 房间ID
     * @return
     * @author Qiang.S
     * @createDate 2018/12/10
     */
    @RequestMapping(path = "/getOwnerPhoneNumber",method = RequestMethod.POST)
    @ResponseBody
    public Object getOwnerPhoneNumber(String roomId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            roomId=request.getAttribute("roomId")==null?null:request.getAttribute("roomId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("roomId",roomId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(roomId)||StringUtils.isBlank(createTime)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            String ownerPhoneNo = iAppHomeServiceClient.getOwnerPhoneNumber(roomId);
            String roomType = iAppHomeServiceClient.getRoomTypeByroomId(roomId);
            List<Map<String, Object>> roleList = iAppProjectServiceClient.getProjectRoleList(roomId);
            JSONObject js = new JSONObject();
            js.put("ownerPhoneNumber",ownerPhoneNo);
            js.put("roomType",roomType);
            js.put("roleIdList", roleList);
            messageVO =  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch (Exception e){
            throw  new DataAccessException("【我的_我的版块_房间业主的电话号码】获取房间业主的电话号码失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *     小程序_我的版块,用户提交房屋认证申请
     * </desc>
     *
     * @param token 申请人用户Token
     * @param appApplyRoomCertificationDTO 用户提交申请房屋认证数据
     * @return
     * @author Qiang.S
     * @createDate 2018/11/20
     */
    @LoggerInfo(operateDesc = LogDescConstant.ROOM_APPLY_CERTIFICATION)
    @RequestMapping(path = "/applyCertification",method = RequestMethod.POST)
    @ResponseBody
    public Object applyRoomCertification(String token, AppApplyRoomCertificationDTO appApplyRoomCertificationDTO, String createTime, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            appApplyRoomCertificationDTO= HttpProtocolUtil.parseRequestParamToDTO(AppApplyRoomCertificationDTO.class,request);
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("roomId",appApplyRoomCertificationDTO.getRoomId());
            params.put("applyHouseType",appApplyRoomCertificationDTO.getApplyHouseType());
            params.put("ownerPhoneNo",appApplyRoomCertificationDTO.getOwnerPhoneNo());
            params.put("certificationType", appApplyRoomCertificationDTO.getCertificationType());
            params.put("smsCode",appApplyRoomCertificationDTO.getSmsCode());
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(appApplyRoomCertificationDTO.getRoomId())||StringUtils.isBlank(appApplyRoomCertificationDTO.getApplyHouseType())){
                //房间ID与申请身份不可为空
                return  new MessageVO(MiniProgramErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            boolean smsSuccess = false;
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY);
           //验证是是否业主认证，认证方式为空时为兼容旧版本不校验
            if(!"1".equals(appApplyRoomCertificationDTO.getApplyHouseType())
                    && appApplyRoomCertificationDTO.getCertificationType() != null
                    && RoomCertificateTypeEnum.HOUSER_CERTIFIFATE.getType().toString().equals(appApplyRoomCertificationDTO.getCertificationType())){
                //非业主时业主手机号与验证码不可为空
                if (StringUtils.isBlank(appApplyRoomCertificationDTO.getSmsCode())){
                    return  new MessageVO(AppErrorCodeEnum.NOT_PARAM.getErrorCode());
                }else {
                    //非业主时核对短信验证码是否正确
                    String smsCodeCache = redisService.get(RedisConstant.REDIS_SMS_CODE+appApplyRoomCertificationDTO.getOwnerPhoneNo());
                    if (!appApplyRoomCertificationDTO.getSmsCode().equals(smsCodeCache)){
                        return new MessageVO(AppErrorCodeEnum.SMSCODE_ERR.getErrorCode());
                    } else if (StringUtils.isBlank(smsCodeCache)){
                        return new MessageVO(AppErrorCodeEnum.SMSCODE_EXPIRE.getErrorCode());
                    }
                    smsSuccess = true;
                }
                if (!NumberHandlerUtil.isPhoneNo(appApplyRoomCertificationDTO.getOwnerPhoneNo())){
                    return new MessageVO(AppErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
                }
            }

            PropertyProjectRoomInfoVO roomInfoPO = iAppProjectServiceClient.getRoomById(appApplyRoomCertificationDTO.getRoomId());
            //检查房间不存在或房间已被删除
            if (roomInfoPO == null||(roomInfoPO != null&&1!=roomInfoPO.getStatus())){
                return  new MessageVO(MiniProgramErrorCodeEnum.ROOM_NOT_EXIST.getErrorCode());
            }
            appApplyRoomCertificationDTO.setUserId(userId);
            appApplyRoomCertificationDTO.setProjectId(roomInfoPO.getProjectId());
            appApplyRoomCertificationDTO.setBuildId(roomInfoPO.getBuildId());
            appApplyRoomCertificationDTO.setUnitId(roomInfoPO.getUnitId());
            appApplyRoomCertificationDTO.setRoomNum(roomInfoPO.getRoomNum());
            appApplyRoomCertificationDTO.setSourceSystem(1);
            appApplyRoomCertificationDTO.setInstructionType(16);
            MessageVO messageVO = iAppHomeServiceClient.applyRoomCertification(appApplyRoomCertificationDTO);
            if (messageVO != null&&0==messageVO.getMsgCode()&&smsSuccess&&StringUtils.isNotBlank(appApplyRoomCertificationDTO.getOwnerPhoneNo())){  //房屋认证业务成功后清除短信验证码缓存
                redisService.del(RedisConstant.REDIS_SMS_CODE+appApplyRoomCertificationDTO.getOwnerPhoneNo());
            }
            return messageVO;
        }catch (Exception e){
            throw  new DataAccessException("【小程序_我的板块_授权认证】用户提交授权认证失败",e);
        }
    }

    /**
     * <desc>
     *    小程序获取验证码
     * </desc>
     * @param phoneNo 手机号或邮箱
     * @return
     * @createDate 2018/11/21
     * @author Qiang.S
     */
    @ResponseBody
    @RequestMapping(path = "/sendMsg",method = RequestMethod.POST)
    public Object appSendSmsCode(String phoneNo,String createTime,String sign) {
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();

            phoneNo=request.getAttribute("phoneNo")==null?null:request.getAttribute("phoneNo").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();

            //验签
            Map<String, String> params = new HashMap<>();
            params.put("phoneNo", phoneNo);
            params.put("createTime", createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            } else if (StringUtils.isEmpty(phoneNo) || StringUtils.isBlank(createTime)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            } else {
                String smsCode = NumberHandlerUtil.randomNum(6);
                boolean sendFlag;  //验证码发送标志,true-发送成功，false-发送失败
                String content = "验证码:" + smsCode + ",该验证码将在30分钟后失效.";
                AppUserInfoPO appUserInfoPO;
                if (!NumberHandlerUtil.isPhoneNo(phoneNo)) { //手机号是否合法
                    return new MessageVO(MiniProgramErrorCodeEnum.PHONE_NOT_MATCH.getErrorCode());
                }
                appUserInfoPO = iAppRegisterServiceClient.getUserByPhoneNo(phoneNo);
                //忘记密码或房屋认证时发送房间业主验证码
                if (appUserInfoPO == null) { //检查手机号码是否已存在
                    return new MessageVO(MiniProgramErrorCodeEnum.NOT_EXIST_PHONENO.getErrorCode());
                }
                //需求10分钟之内可以发送3条
                //按顺序放入缓存3条如果都存在则报错,每条10分钟超时
                int count1 = redisService.get(RedisConstant.REDIS_SMS_TIMES + "1" + phoneNo) == null ? 0 : 1;
                int count2 = redisService.get(RedisConstant.REDIS_SMS_TIMES + "2" + phoneNo) == null ? 0 : 1;
                int count3 = redisService.get(RedisConstant.REDIS_SMS_TIMES + "3" + phoneNo) == null ? 0 : 1;
                if (count1 != 0 && count2 != 0 && count3 != 0) {//都不为空证明已经发了3次
                    ErrorCode errorCode = MiniProgramErrorCodeEnum.SMSCODE_SEND_TO_MORE.getErrorCode();
                    return new MessageVO(errorCode);
                }
                if (count1 == 0) {
                    redisService.set(RedisConstant.REDIS_SMS_TIMES + "1" + phoneNo, RedisConstant.SMS_TIMES_TIME, "1");
                } else if (count2 == 0) {
                    redisService.set(RedisConstant.REDIS_SMS_TIMES + "2" + phoneNo, RedisConstant.SMS_TIMES_TIME, "1");
                } else if (count3 == 0) {
                    redisService.set(RedisConstant.REDIS_SMS_TIMES + "3" + phoneNo, RedisConstant.SMS_TIMES_TIME, "1");
                }
                sendFlag = iIotTpSmsServiceClient.sendSmsCodeByPhone(phoneNo, content);
                if (sendFlag) {
                    boolean redisFlag;
                    redisFlag = redisService.set(RedisConstant.REDIS_SMS_CODE + phoneNo, RedisConstant.SMS_CODE_TIME, smsCode);
                    if (redisFlag) {
                        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
                    } else {
                        LOG.info("【小程序_我的模块_获取验证码缓存验证码失败】");
                        return new MessageVO(MiniProgramErrorCodeEnum.SMSCODE_SEND_ERR.getErrorCode());
                    }
                }
                return new MessageVO(MiniProgramErrorCodeEnum.SMSCODE_SEND_ERR.getErrorCode());
            }
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的模块_获取验证码】获取验证码失败", e);
        }
    }

    /**
     *  <desc>
     *      获取所有城市信息列表,首字母分组及城市ID与城市名称
     *  </desc>
     * @return
     * @createDate 2018/11/21
     * @author Qiang.S
     */
    @RequestMapping(path = "/getCitys",method = RequestMethod.POST)
    @ResponseBody
    public Object getCitys() throws  Exception{
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String encryptScript = request.getParameter("encryptScript");
            if (StringUtils.isBlank(encryptScript)) {
                List<AppProjectAddressVO> projectAddressList = iAppProjectAddressServiceClient.getAllUsedCityInitials();
                return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),projectAddressList);
            }
            AppNewProjectAddressVO projectAddress = iAppProjectAddressServiceClient.getNewAllUsedCityInitials();
            return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),projectAddress);

        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块_城市列表】获取城市列表失败",e);
        }
    }

    /**
     *  <desc>
     *      获取所有城市信息列表,首字母分组及城市ID与城市名称
     *  </desc>
     * @return
     * @createDate 2019/09/19
     * @author Juguang.S
     */
    @RequestMapping(path = "/getCitysForMiniVisitor",method = RequestMethod.POST)
    @ResponseBody
    public Object getCitysForMiniVisitor() throws  Exception{
        try {
            List<AppProjectAddressVO> projectAddressList = iAppProjectAddressServiceClient.getAllUsedCityInitials();
            return  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),projectAddressList);
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块_城市列表】获取城市列表失败",e);
        }
    }

    /**
     * <desc>
     *      根据城市ID获取启用状态的项目信息（项目编号与项目名称）
     * </desc>
     * @param cityId 城市ID
     * @return
     * @createDate 2018/11/22
     *  @author Qiang.S
     */
    @RequestMapping(path = "/getProjectsInCity",method = RequestMethod.POST)
    @ResponseBody
    public Object getProjectsInCity(String cityId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            cityId=request.getAttribute("cityId")==null?null:request.getAttribute("cityId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("cityId",cityId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(cityId)||StringUtils.isBlank(createTime)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            JSONObject js = new JSONObject();
            List<AppProjectBuildVO> list = iAppProjectServiceClient.getNewProjectsInCity(cityId);
            js.put("projects",list);
            messageVO =  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch (Exception e){
            throw new DataAccessException("【小程序2.0】获取项目信息列表失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      根据楼栋ID获取启用状态的项目信息（项目编号与项目名称）
     * </desc>
     * @param buildId 楼栋ID
     * @return
     * @createDate 2019/08/28
     * @author Juguang.S
     */
    @RequestMapping(path = "/getProjectsInCityByBuildId",method = RequestMethod.POST)
    @ResponseBody
    public Object getProjectsInCityByBuildId(String buildId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            buildId=request.getAttribute("buildId")==null?null:request.getAttribute("buildId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("buildId",buildId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(buildId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            JSONObject js = new JSONObject();
            List<AppProjectRoomVO> list = iAppProjectServiceClient.getNewProjectsUnit(buildId);
            js.put("projects",list);
            messageVO =  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch (Exception e){
            throw new DataAccessException("【小程序2.0】获取项目信息列表失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      获取访客通行密码记录
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return 格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/26
     */
    @ResponseBody
    @PostMapping("/getVisitorPassCodePage")
    public Object getVisitorRecord(AppGetVisitorRecordPageDTO dto, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto=HttpProtocolUtil.parseRequestParamToDTO(AppGetVisitorRecordPageDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            if (dto == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",dto.getProjectId());
            params.put("pageNo",dto.getPageNo());
            params.put("pageSize",dto.getPageSize());
            params.put("createTime",dto.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(dto.getProjectId())||StringUtils.isBlank(dto.getToken())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(dto.getToken(), MINI_PROGRAM_USER_TOKEN_KEY);
            dto.setLoginUserId(userId);
            Page<AppGetVisitorRecordPageVO> page = iAppVisitorPassCodeRecordServiceClient.getPage(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_访客通行】获取访客通行列表失败",e);
        }
    }

    /**
     * <desc>
     *      根据访客编号获取信息
     * </desc>
     *
     * @param passId 访客编号
     * @param createTime 创建时间
     * @param sign 签名
     * @return 格式化响应结果
     * @author Qiang.S
     * @createDate 2019/04/24
     */
    @ResponseBody
    @UnAuthAccessRequired
    @PostMapping("/getVisitorPassByPassId")
    public Object getVisitorPassByPassId(String  passId,String createTime, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            passId=request.getAttribute("passId")==null?null:request.getAttribute("passId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("passId",passId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(passId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iAppVisitorPassCodeRecordServiceClient.getVisitorPassByPassId(passId));
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_访客通行】根据访客编号获取信息失败",e);
        }
    }

    /**
     * <desc>
     *      根据用户编号查询所有设备信息
     * </desc>
     *
     * @param projectId 项目编号
     * @return
     *  @author Qiang.S
     * @createDate 2018/11/26
     */
    @RequestMapping(path = "/myEquipInfo",method = RequestMethod.POST)
    @ResponseBody
    public Object myEquipInfo(String projectId,String token,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(createTime) || StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY);
            List<MiniProgramMyEquipListVO> miniProgramMyEquipListVOS = iMiniProgramEquipServiceClient.myEquipInfo(userId, projectId);

            //常用楼层
            String userCommonFloor = iAppDeviceServiceClient.getUserCommonFloor(userId, projectId);
            Map<String, Object> userCommonFloorMap = null;
            if (StringUtils.isNotBlank(userCommonFloor)) {
                userCommonFloorMap = JSON.parseObject(userCommonFloor, HashMap.class);
            }
            //常用公共楼层
            String userPublicFloor = iAppDeviceServiceClient.getUserPublicFloor(userId, projectId);
            Map<String, Object> userPublicFloorMap = null;
            if (StringUtils.isNotBlank(userPublicFloor)) {
                userPublicFloorMap = JSON.parseObject(userPublicFloor, HashMap.class);
            }
            //常用楼层和常用公共楼层筛选
            if(miniProgramMyEquipListVOS!=null&& miniProgramMyEquipListVOS.size()>0){
                for (MiniProgramMyEquipListVO miniProgramMyEquipListVO : miniProgramMyEquipListVOS) {
                    if (userCommonFloorMap != null && !userCommonFloorMap.isEmpty()) {
                        miniProgramMyEquipListVO.setLiveChoiceFloor(
                                userCommonFloorMap.get(miniProgramMyEquipListVO.getDeviceUnique()) == null ?
                                        "" : userCommonFloorMap.get(miniProgramMyEquipListVO.getDeviceUnique()).toString());
                    }
                    if (userPublicFloorMap != null && !userPublicFloorMap.isEmpty()) {
                        miniProgramMyEquipListVO.setCommonChoiceFloor(
                                userPublicFloorMap.get(miniProgramMyEquipListVO.getDeviceUnique()) == null ?
                                        "" : userPublicFloorMap.get(miniProgramMyEquipListVO.getDeviceUnique()).toString());
                    }

                    //权限去冗余，物业后台可能会将这个选中的常用或者公共楼层移除权限
                    //然后需要检查对应的choice选项，如果权限没有了，choice要置为空
                    String  allFloorStr  =   miniProgramMyEquipListVO.getFloors();
                    List<String>  allFloorList =  new ArrayList<String>();
                    if(StringUtils.isNotEmpty(allFloorStr)){
                        allFloorList  =  Arrays.asList(allFloorStr.split(","));
                    }
                    String  cCFloor   =  miniProgramMyEquipListVO.getCommonChoiceFloor();
                    String  lCFloor     =  miniProgramMyEquipListVO.getLiveChoiceFloor();
                    if(  (!allFloorList.contains(cCFloor))  &&  (!"x".equals(cCFloor))){
                        miniProgramMyEquipListVO.setCommonChoiceFloor("");
                    }
                    if(  (!allFloorList.contains(lCFloor))  &&  (!"x".equals(lCFloor))){
                        miniProgramMyEquipListVO.setLiveChoiceFloor("");
                    }
                }
            }
            messageVO =  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), miniProgramMyEquipListVOS);
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块_根据用户编号查询所有设备信息myEquipInfo】根据用户编号查询所有设备信息失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      获取用户有通行记录的日期分页列表
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return
     * @author Qiang.S
     * @createDate 2018/11/26
     */
    @RequestMapping(path = "/datelist",method = RequestMethod.POST)
    @ResponseBody
    public Object getVisitorRecord(AppGetDateListPageDTO dto, String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto=HttpProtocolUtil.parseRequestParamToDTO(AppGetDateListPageDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(dto,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getProjectId()) || !dto.getProjectId().matches("[0-9]{8}")){
                LOG.info("【小程序_我的版块】获取用户有通行记录的日期分页列表_项目编号非法】"+dto.getProjectId());
                return  new MessageVO(MiniProgramErrorCodeEnum.PROJECT_NOT_MATCH.getErrorCode());
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(dto.getToken(), MINI_PROGRAM_USER_TOKEN_KEY);
            dto.setLoginUserId(userId);
            //查询
            Page<String> page=iAppDevicePassRecordServiceClient.getPassDateListPage(dto);
            Map<String,Object> map=new HashMap<>();
            page.getRows().forEach(row->{
                if(StringUtils.isBlank(row)){
                    row="";
                }
            });
            map.put("date",page.getRows());
            map.put("pageCount",page.getPage().getTotalPage());
            messageVO=new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块】获取用户有通行记录的日期分页列表失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取用户通行记录列表
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return
     * @author Qiang.S
     * @createDate 2018/11/26
     */
    @RequestMapping(path = "/dateRecordlist",method = RequestMethod.POST)
    @ResponseBody
    public Object dateRecordlist(AppGetPassRecordListPageDTO dto, String sign) {
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto=HttpProtocolUtil.parseRequestParamToDTO(AppGetPassRecordListPageDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验证签名
            if (!Md5EncryptUtil.checkAppSignValue(dto, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(dto.getProjectId()) || !dto.getProjectId().matches("[0-9]{8}")) {
                LOG.info("【小程序_我的版块】获取用户通行记录列表_项目编号非法】" + dto.getProjectId());
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_NOT_MATCH.getErrorCode());
            }
            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(dto.getToken(), MINI_PROGRAM_USER_TOKEN_KEY);
            dto.setLoginUserId(userId);
            //查询
            Page<AppGetPassRecordListPageVO> page = iAppDevicePassRecordServiceClient.getPage(dto);
//            page.getRows().forEach(row -> {
//                row = (AppGetPassRecordListPageVO) StringHandlerUtil.formatString(row);
//            });
            Map<String, Object> map = new HashMap<>();
            map.put("recordlist", page.getRows());
            map.put("pageCount", page.getPage().getTotalPage());
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), map);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块】获取用户通行记录列表失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取已邀请家人列表
     * </desc>
     *
     * @param pageDTO 接收数据dto类
     * @param sign 签名
     * @return 格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/26
     */
    @ResponseBody
    @PostMapping("/getInvitePersonPage")
    public Object getInvitePersonPage(AppGetAuthPersonPageDTO pageDTO, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO=HttpProtocolUtil.parseRequestParamToDTO(AppGetAuthPersonPageDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            if (pageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",pageDTO.getProjectId());
            params.put("pageNo",pageDTO.getPageNo());
            params.put("pageSize",pageDTO.getPageSize());
            params.put("createTime",pageDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(pageDTO.getProjectId())||StringUtils.isBlank(pageDTO.getToken())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(pageDTO.getToken(), MINI_PROGRAM_USER_TOKEN_KEY);
            pageDTO.setLoginUserId(userId);
            Page<AppMineGetAuthPersonPageVO> authPersonPageVOPage =iAppMineServiceClient.getAuthPersonPage(pageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),authPersonPageVOPage);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_邀请家人】获取已邀请家人列表失败",e);
        }
    }

    /**
     * <desc>
     *      获取家人房间信息
     * </desc>
     *
     * @param pageDTO 接收数据dto类
     * @param sign 签名
     * @return 格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/27
     */
    @ResponseBody
    @PostMapping("/getAuthPersonRoom")
    public Object getAuthPersonRoom(AppAuthPersonGetRoomInfoDTO pageDTO, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            pageDTO=HttpProtocolUtil.parseRequestParamToDTO(AppAuthPersonGetRoomInfoDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            if (pageDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",pageDTO.getProjectId());
            params.put("authPhoneNo",pageDTO.getAuthPhoneNo());
            params.put("createTime",pageDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(pageDTO.getProjectId())||StringUtils.isBlank(pageDTO.getToken())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(pageDTO.getToken());
            if(null == userInfo){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            pageDTO.setLoginUserId(userInfo.getUserId());
            List<AppMineGetAddressInfoVO> addressInfoList = iAppMineServiceClient.getAuthPersonRoomInfo(pageDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), addressInfoList);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_邀请家人】获取家人房间信息失败",e);
        }
    }

    /**
     * <desc>
     *      邀请家人(添加授权人)
     * </desc>
     *
     * @param saveDTO 接收数据dto类
     * @param sign 签名
     * @return 格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/27
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_ADD_AUTHPERSON_INFO)
    @ResponseBody
    @PostMapping("/invitePerson")
    public Object invitePerson(AppMineSaveAuthPersonDTO saveDTO, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            saveDTO=HttpProtocolUtil.parseRequestParamToDTO(AppMineSaveAuthPersonDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            int houserType=request.getAttribute("houserType")==null?2:Integer.parseInt(request.getAttribute("houserType").toString());
            if (saveDTO == null) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",saveDTO.getProjectId());
            params.put("authPhoneNo",saveDTO.getAuthPhoneNo());
            params.put("userRemarks",saveDTO.getUserRemarks());
            params.put("roomNums",saveDTO.getRoomNums());
            params.put("type",saveDTO.getType());
            params.put("houserType",houserType + "");
            params.put("createTime",saveDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(saveDTO.getProjectId())||StringUtils.isBlank(saveDTO.getToken()) || StringUtils.isBlank(saveDTO.getAuthPhoneNo())
                    || StringUtils.isBlank(saveDTO.getUserRemarks()) || StringUtils.isBlank(saveDTO.getRoomNums()) || StringUtils.isBlank(saveDTO.getType())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(saveDTO.getToken());
            if(null == userInfo){
                return new MessageVO(MiniProgramErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
            }
            //判断是否使用云对讲  0-否，1-是
            Integer isSmartCommunity = iOperateProjectServiceClient.getIsSmartCommunity(saveDTO.getProjectId());
            if (isSmartCommunity == null) {
                LOG.info("【小程序_我的版块】添加授权人_项目编号非法】" + saveDTO.getProjectId());
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_NOT_MATCH.getErrorCode());
            }
            String roomIdArr[] = StringHandlerUtil.splitString(saveDTO.getRoomNums());
            //获取被授权的用户信息
            AppUserInfoPO authUserInfo = iAppMineServiceClient.getUserInfoByPhoneNo(saveDTO.getAuthPhoneNo());
            String userId = "";
            if (authUserInfo != null) {
                userId = authUserInfo.getUserId();
            }
            for (int i = 0; i < roomIdArr.length; i++) {
                //已经授权的数目
                userId = StringUtils.isNotBlank(userId) ? userId : "";
                //获取该房屋类型 1住宅 2办公
                Integer housesType = iPropertyHouseHoldInfoServiceClient.getHousesType(roomIdArr[i], saveDTO.getProjectId());
                Integer alreadyAuthNum = iAppMineServiceClient.getUserRoomCount(userId, saveDTO.getProjectId(), roomIdArr[i]);
                //查询当前项目信息
                ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(saveDTO.getProjectId());
                //一个房间最大邀请人数是包括业主在内的人数
                Integer maxAuthNum = projectPO.getAuthMaxNum();
                Integer officeMaxAuthNum = projectPO.getOfficeAuthMaxNum();
                if(officeMaxAuthNum==0){
                    officeMaxAuthNum=11;
                }
                if (maxAuthNum == null || maxAuthNum == 0) {
                    return new MessageVO(MiniProgramErrorCodeEnum.NOT_ADD_OPENAUTH_ERROR.getErrorCode());
                }
                if (housesType==1 && alreadyAuthNum >= maxAuthNum) {
                    String roomName = iAppMineServiceClient.getRoomName(saveDTO.getProjectId(), roomIdArr[i]);
                    //房间入住人数已满
                    String errInfo = String.format(MiniProgramErrorCodeEnum.ROOM_NUM_MAX_ERROR.getCodeMsg(), roomName);
                    return new MessageVO(MiniProgramErrorCodeEnum.ROOM_NUM_MAX_ERROR.getErrorCode(), errInfo);
                }
                if(housesType==3 && alreadyAuthNum>=officeMaxAuthNum){
                    String roomName = iAppMineServiceClient.getRoomName(saveDTO.getProjectId(),roomIdArr[i]);
                    //办公房间入住人数已满
                    String errInfo = String.format(AppErrorCodeEnum.ROOM_NUM_MAX_ERROR.getCodeMsg(),roomName);
                    return new MessageVO(AppErrorCodeEnum.ROOM_NUM_MAX_ERROR.getErrorCode(),errInfo);
                }
            }
            //获取当前项目的状态 0 冻结 1启用
            Integer userProjectStatus = iAppMineServiceClient.getAppUserProjectStatus(userInfo.getUserId(),saveDTO.getProjectId());
            //冻结
            if(AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_FROZEN.getType().equals(userProjectStatus)){
//                String errInfo = String.format(MiniProgramErrorCodeEnum.USER_PROJECT_FREEZE_NOT_AUTH.getCodeMsg(),userInfo.getCurrentProjectName());
//                return new MessageVO(MiniProgramErrorCodeEnum.USER_PROJECT_FREEZE_NOT_AUTH.getErrorCode(),errInfo);
                return new MessageVO(MiniProgramErrorCodeEnum.USER_PROJECT_FREEZE_NOT_AUTH.getErrorCode());
            }
            //判断授权用户是否是业主自己
            if(userInfo.getUserId().equals(userId)){
                return new MessageVO(MiniProgramErrorCodeEnum.ADD_AUTHPERSON_SELF_ERROR.getErrorCode());
            }
            if ("1".equals(saveDTO.getType())) {
                Integer countUserId = iAppMineServiceClient.getUserAuthRelationCount(userInfo.getUserId(), userId, saveDTO.getProjectId());
                if (countUserId > 0) {
                    //存在该用户，不能重新添加房间信息
                    if (StringUtils.isNotEmpty(saveDTO.getUserRemarks())) {
                        return new MessageVO(MiniProgramErrorCodeEnum.ADD_AUTHPERSON_EXIT_ERROR.getErrorCode());
                    }
                }
            }
            AppMineAuthPersonExtendDTO extendDTO = new AppMineAuthPersonExtendDTO(userId,saveDTO.getProjectId(),saveDTO.getAuthPhoneNo(),saveDTO.getUserRemarks(),saveDTO.getRoomNums(),isSmartCommunity);
            extendDTO.setLoginUserId(userInfo.getUserId());
            extendDTO.setHouserType(houserType);
            //检测是否是新用户
            if (StringUtils.isBlank(userId) && (authUserInfo == null)) {
                AppUserInfoPO appUserInfoPO = new AppUserInfoPO();
                appUserInfoPO.setUserId(LogicIdUtil.userBusinessId());
                String phoneNo = saveDTO.getAuthPhoneNo();
                String nickName = String.format("%s%s", "U_", phoneNo.substring(phoneNo.length() - 4, phoneNo.length()));
                appUserInfoPO.setNickName(nickName);
                appUserInfoPO.setPhoneNum(phoneNo);
                appUserInfoPO.setToken(UserTokenUtil.tokenEncrypt(appUserInfoPO.getUserId(), MINI_PROGRAM_USER_TOKEN_KEY, SystemTypeEnum.MINI_PROGRAM.getType()));
                appUserInfoPO.setStatus(1);
                appUserInfoPO.setCreateTime(new Date());
                //新用户
                extendDTO.setUserId(appUserInfoPO.getUserId());
                extendDTO.setAppUserInfoPO(appUserInfoPO);
            } else {  //用户状态
                extendDTO.setStatus(authUserInfo.getStatus());
            }
            //添加用户信息
            Map<String, Object> resultMap= iAppMineServiceClient.addAuthPerson(extendDTO);
            if(!"true".equals(resultMap.get("returnCode").toString())){
                return  new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),resultMap.get("hintInfo").toString());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_邀请家人】邀请家人(添加授权人)失败",e);
        }
    }

    /**
     * <desc>
     *      删除授权人
     * </desc>
     *
     * @return 格式化响应结果
     * @author wangzhi
     * @createDate 2018/11/27
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_DEL_AUTHPERSON_INFO)
    @ResponseBody
    @PostMapping("/deleteAuthPerson")
    public Object deleteAuthPerson(String token,String projectId, String authPhoneNo,String createTime,String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            authPhoneNo=request.getAttribute("authPhoneNo")==null?null:request.getAttribute("authPhoneNo").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("authPhoneNo",authPhoneNo);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(authPhoneNo) || StringUtils.isBlank(token) || StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(token);
            if(null == userInfo){
                return new MessageVO(MiniProgramErrorCodeEnum.USER_TOKEN_ERROR.getErrorCode());
            }
            //获取当前项目的状态 0 冻结 1启用
            Integer userProjectStatus = iAppMineServiceClient.getAppUserProjectStatus(userInfo.getUserId(),projectId);
            //冻结
            if(AppUserProjectStatusEnum.USERPROJECT_USERPROJECTSTATUS_FROZEN.getType().equals(userProjectStatus)){
                return new MessageVO(MiniProgramErrorCodeEnum.USER_PROJECT_FREEZE_NOT_AUTH.getErrorCode());
            }
            boolean isSuccess = iAppMineServiceClient.deleteAuthPerson(userInfo.getUserId(),authPhoneNo,projectId);
            if(!isSuccess){
                return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_邀请家人】删除家人(删除授权人)失败",e);
        }
    }

    /**
     * <desc>
     *      获取通行密码
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return
     * @author Qiang.S
     * @createDate 2018/11/28
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_GETVISITPASSWORD_ERROR)
    @RequestMapping(path = "/getVisitPassWord",method = RequestMethod.POST)
    @ResponseBody
    public Object getVisitPassWord(AppGetVisitPassWordDTO dto,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String encryptScript = request.getParameter("encryptScript");
            dto=HttpProtocolUtil.parseRequestParamToDTO(AppGetVisitPassWordDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            Map<String,String> params = new HashMap<>();
            params.put("visitorName",dto.getVisitorName());
            params.put("visitorPhoneNumber",dto.getVisitorPhoneNumber());
            params.put("roomId",dto.getRoomId());
            params.put("projectId",dto.getProjectId());
            params.put("createTime",dto.getCreateTime());
            params.put("facePicUrl",dto.getFacePicUrl());
            if(dto.getVisitorReservationMark()==1){
                params.put("visitTime",dto.getVisitTime());
                params.put("intervieweePhone",dto.getIntervieweePhone());
                params.put("plateNumber",dto.getPlateNumber());
                params.put("visitorReservationMark",dto.getVisitorReservationMark().toString());
                params.put("visitorCause",dto.getVisitorCause());
            }else{
                //此处判断为兼容新旧版本问题
                if (!StringUtils.isBlank(encryptScript)) {
                    params.put("deviceUniques",dto.getDeviceUniques());
                }
                params.put("countLimit",dto.getCountLimit());
                params.put("timeLimit",dto.getTimeLimit());
                params.put("visitTime",dto.getVisitTime());
            }
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }

            if (StringUtils.isBlank(dto.getProjectId()) || !dto.getProjectId().matches("[0-9]{8}")){
                LOG.info("【小程序_我的版块】获取通行密码_项目编号非法】"+dto.getProjectId());
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_NOT_MATCH.getErrorCode());
            }else if(StringUtils.isBlank(dto.getVisitorName())){
                return new MessageVO(MiniProgramErrorCodeEnum.VISIT_NAME_IS_NULL.getErrorCode());
            }else if(dto.getVisitorName().length() > 10){
                return new MessageVO(MiniProgramErrorCodeEnum.VISIT_NAME_IS_ERROR.getErrorCode());
            }else if(StringUtils.isBlank(dto.getVisitorPhoneNumber())){
                return new MessageVO(MiniProgramErrorCodeEnum.VISIT_PHONE_IS_NULL.getErrorCode());
            }else if(!dto.getVisitorPhoneNumber().matches("[0-9]{11}")){
                return new MessageVO(MiniProgramErrorCodeEnum.VISIT_PHONE_IS_ERROR.getErrorCode());
            }
            //如果是业主身份的访客预约则需校验是否预约的自己的房间
            if(dto.getVisitorReservationMark()==1){
                //根据手机号获取userId
                String userId = iPropertyRoomInfoServiceClient.getUserIdByPhone(dto.getVisitorPhoneNumber());
                if(StringUtils.isNotEmpty(userId)){
                    List<MiniProgramPassRoomListVO> list = iPropertyRoomInfoServiceClient.myRoomsInfo(userId,dto.getProjectId());
                    List<String> roomList = new ArrayList<>();
                    for(MiniProgramPassRoomListVO roomListVO : list){
                        roomList.add(roomListVO.getRoomId());
                    }
                    String roomStr = StringUtils.join(roomList.toArray(),",");
                    if(roomStr.contains(dto.getRoomId())){
                        return new MessageVO(MiniProgramErrorCodeEnum.NOT_ALLOWED_VISITOR.getErrorCode());
                    }
                }
            }

            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(dto.getToken());
            dto.setLoginUserId(userInfo.getUserId());
            dto.setLoginUserPhone(userInfo.getPhoneNo());
            dto.setSource(VisitorSourceTypeEnum.MINI.getType());
            AppVisitorPassCodeRecordPO po=iAppVisitorPassCodeRecordServiceClient.save(dto);
            if(po.getResult().equals("SUCCESS")) {
                MiniGetVisitPassWordVO vo = new MiniGetVisitPassWordVO();
                vo.setPassId(po.getPassId());
                vo.setPassWord(po.getPassword());
                vo.setStartTime(DateUtil.fomatDate(po.getStartTime(), DateUtil.YYYYMMDDHHMM));
                vo.setEndTime(DateUtil.fomatDate(po.getEndTime(), DateUtil.YYYYMMDDHHMM));
                vo.setVisitorPhoneNo(po.getVisitorPhone());
                vo.setVisitorName(po.getVisitorName());
                vo.setQrCodeUrl(po.getQrcodeUrl());
                if(StringUtils.isNotBlank(po.getBuildId())){
                    vo.setAddress(iAppVisitorPassCodeRecordServiceClient.getAddress(po.getBuildId(), po.getUnitId(), po.getRoomId()));
                }
                vo = (MiniGetVisitPassWordVO) StringHandlerUtil.formatString(vo);
                if (vo.getPassWord() == null || vo.getPassWord().isEmpty()) {
                    return new MessageVO(AppErrorCodeEnum.NO_DEVICE_AUTH.getErrorCode(), vo);
                }
                if (dto.getFacePicUrl() != null && !"".equals(dto.getFacePicUrl())) {
                    MiniSetVisitPassFaceDTO miniSetVisitPassFaceDTO = new MiniSetVisitPassFaceDTO();
                    if (dto.getFacePicUrl().contains("http://") || dto.getFacePicUrl().contains("https://")) {
                        dto.setFacePicUrl(dto.getFacePicUrl().replace("https://","http://"));
                        if(dto.getFacePicUrl().contains("test.img.jia-r.com")){
                            dto.setFacePicUrl(dto.getFacePicUrl().replace("test01.img.jia-r.com","139.9.30.74:8080"));
                        }else if(dto.getFacePicUrl().contains("temporary.img.jia-r.com")){
                            dto.setFacePicUrl(dto.getFacePicUrl().replace("test02.img.jia-r.com","139.9.29.205:8080"));
                        }else if(dto.getFacePicUrl().contains("tmp.img.jia-r.com")){
                            dto.setFacePicUrl(dto.getFacePicUrl().replace("tmp.img.jia-r.com","139.9.29.205:8080"));
                        }else if(dto.getFacePicUrl().contains("develop.img.jia-r.com")){
                            dto.setFacePicUrl(dto.getFacePicUrl().replace("develop.img.jia-r.com","139.9.29.180:8080"));
                        }else if(dto.getFacePicUrl().contains("//img.jia-r.com")){
                            dto.setFacePicUrl(dto.getFacePicUrl().replace("//img.jia-r.com","//119.3.89.69:8080"));
                        }
                        byte[] imageStr = VerifyCodeUtils.getFileStream(dto.getFacePicUrl(), propertyOperateMiniContentAesEncryptKey);
                        dto.setBtImg(imageStr);
                        miniSetVisitPassFaceDTO.setBtImg(dto.getBtImg());
                        miniSetVisitPassFaceDTO.setMark(1);
                    }
                    miniSetVisitPassFaceDTO.setImageStr(dto.getFacePicUrl());
                    miniSetVisitPassFaceDTO.setPassId(po.getPassId());
                    miniSetVisitPassFaceDTO.setProjectId(dto.getProjectId());
                    miniSetVisitPassFaceDTO.setVisitorReservationMark(dto.getVisitorReservationMark());
                    messageVO = this.setVisitPassFacePrivate(miniSetVisitPassFaceDTO);
                    if (messageVO.getMsgCode() != 0) {
                        iAppVisitorPassCodeRecordServiceClient.deleteVisitorInfo(po.getPassId());
                        return messageVO;

                    }
                    Map<String, String> map = (Map<String, String>) messageVO.getData();
                    vo.setResult(map.get("result"));
                    vo.setAuthDate(map.get("authDate"));
                    vo.setFacePicUrl(map.get("uploadFilePath"));
                }
                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), vo);
                if (dto.getVisitorReservationMark() == 1) {
                    //此处需要判断项目是否配置物业是否需要审批
                    OperateProjectDetailVO operateProjectDetailVO = iOperateProjectServiceClient.getDetail(dto.getProjectId());
                    WeChatVisitorMsgDTO msgDTO = new WeChatVisitorMsgDTO();
                    if (operateProjectDetailVO.getMiniVisitorOwner() == 0) {
                        msgDTO.setOperateType(VisitorOperateTypeEnum.NEED_PROPERTY_CHECK.getType().toString());
                    } else {
                        msgDTO.setOperateType(VisitorOperateTypeEnum.SUBMIT_VISITOR_LIST.getType().toString());
                    }
                    msgDTO.setPassId(po.getPassId());
                    iWeChatTemplateMsgServiceClient.sendWeChatTemplateMsg(msgDTO);
                }
            }else if(po.getResult().equals("TIME")){
                if(dto.getVisitorReservationMark()!=null && dto.getVisitorReservationMark()==1){
                    messageVO = new MessageVO(AppErrorCodeEnum.ADD_VISITOR_ERROR_2.getErrorCode(),"房间二维码授权已过有效期，添加访客失败");
                }else {
                    messageVO = new MessageVO(AppErrorCodeEnum.ADD_VISITOR_ERROR_2.getErrorCode());
                }
            }else{
                Integer count = Integer.valueOf(po.getResult());
                if(dto.getVisitorReservationMark()!=null && dto.getVisitorReservationMark()==1){
                    if (count > 0) {
                        messageVO = new MessageVO(AppErrorCodeEnum.ADD_VISITOR_ERROR_3.getErrorCode(),
                                String.format("房间当前剩余通行次数为%s次，仅能创建≤%s次通行次数，添加访客失败", po.getResult(), po.getResult()));
                    } else {
                        messageVO = new MessageVO(AppErrorCodeEnum.ADD_VISITOR_ERROR_1.getErrorCode(),
                                String.format("房间当前剩余通行次数为%s次，添加访客失败", po.getResult()));
                    }
                }else {
                    if (count > 0) {
                        messageVO = new MessageVO(AppErrorCodeEnum.ADD_VISITOR_ERROR_3.getErrorCode(),
                                String.format("您当前剩余通行次数为%s次，仅能创建≤%s次通行次数，添加访客失败", po.getResult(), po.getResult()));
                    } else {
                        messageVO = new MessageVO(AppErrorCodeEnum.ADD_VISITOR_ERROR_1.getErrorCode(),
                                String.format("您当前剩余通行次数为%s次，添加访客失败", po.getResult()));
                    }
                }
            }
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块】获取通行密码失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      保存访客人脸
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return
     * @author Qiang.S
     * @createDate 2019/02/26
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_GETVISITPASS_FACE)
    @RequestMapping(path = "/setVisitPassFace",method = RequestMethod.POST)
    @ResponseBody
    @UnAuthAccessRequired
    public Object setVisitPassFace(MiniSetVisitPassFaceDTO dto, String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto=HttpProtocolUtil.parseRequestParamToDTO(MiniSetVisitPassFaceDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验证签名
            Map<String,String> params = new HashMap<>();
            params.put("projectId",dto.getProjectId());
            params.put("imageStr",dto.getImageStr());
            params.put("passId",dto.getPassId());
            params.put("createTime",dto.getCreateTime());
            if(dto.getVisitorReservationMark()==1){
                params.put("visitorReservationMark",dto.getVisitorReservationMark().toString());
            }
            if(StringUtils.isBlank(dto.getProjectId())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(dto.getVisitorReservationMark()==1){
                //校验该访客记录如是已被物业审批并且已认证过则不允许其再进行二次认证
                if(iAppVisitorPassCodeRecordServiceClient.isAllowedAuthenticate(dto.getPassId())>0){
                    return new MessageVO(MiniProgramErrorCodeEnum.VISITOR_CHECKED_NOT_ALLOWED_AUTH.getErrorCode());
                }
            }
            messageVO = this.setVisitPassFacePrivate(dto);
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块】保存访客人脸失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      保存访客人脸(私有)
     * </desc>
     *
     * @param dto 接收数据dto类
     * @return
     * @author Qiang.S
     * @createDate 2019/02/26
     */
    private MessageVO setVisitPassFacePrivate(MiniSetVisitPassFaceDTO dto) throws Exception{

        if (StringUtils.isBlank(dto.getImageStr())){
            return new MessageVO(AppErrorCodeEnum.IMAGE_DATA_INVALID.getErrorCode());
        }
        String uploadFilePath = "";
        if(dto.getMark()==1){
            uploadFilePath = uploadImageFileForByte(dto.getBtImg(), "jpg", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
        }else{
            uploadFilePath = uploadImageFile(dto.getImageStr(), "jpg", FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
        }
        //LOG.info("【小程序创建访客上传人脸url】："+uploadFilePath);

        if (StringUtils.isBlank(uploadFilePath)) {
            return new MessageVO(AppErrorCodeEnum.IMAGE_UPLOAD_FAILED.getErrorCode());
        }
        Map<String, String> map = new HashMap<>();
        //判断项目是否开启人脸识别,并查询是否有百度库key
        OperateFaceApplyInfoVO operateFaceApplyInfoVO = iOperateFaceApplyServiceClient.getFaceByProjectId(dto.getProjectId());
        if(operateFaceApplyInfoVO == null){
            ErrorCode errorCode = AppErrorCodeEnum.PROJECT_FACE_APPID_INEXISTENCE.getErrorCode();
            return new MessageVO(errorCode);
        }
        //访客人脸注册时,判断人脸库中是否有此人数据
        AppCreateBaiduFaceVO appCreateBaiduFaceVO = new AppCreateBaiduFaceVO();
        appCreateBaiduFaceVO.setAPP_ID(operateFaceApplyInfoVO.getAppId());
        appCreateBaiduFaceVO.setAPI_KEY(operateFaceApplyInfoVO.getApiKey());
        appCreateBaiduFaceVO.setSECRET_KEY(operateFaceApplyInfoVO.getSecretKey());
        appCreateBaiduFaceVO.setFaceScore(operateFaceApplyInfoVO.getFaceScore()==0F?80F:operateFaceApplyInfoVO.getFaceScore());
//        if (dto.getMark()==1) {
//            appCreateBaiduFaceVO.setFile(dto.getBtImg());
//        }else {
//            String imageStr = URLDecoder.decode(dto.getImageStr(), "UTF-8");
//            appCreateBaiduFaceVO.setFile(new BASE64Decoder().decodeBuffer(imageStr));
//        }
        appCreateBaiduFaceVO.setImageUrl(uploadFilePath);
        String checkResult = iIotBaiduFaceServiceClient.faceVerify(appCreateBaiduFaceVO);
        if (checkResult != null && !"".equals(checkResult)) {
            if ("error".equals(checkResult)) {//调用接口异常
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACEVERFY_ERROR.getErrorCode());
            }
            if ("busy".equals(checkResult)) {//调用接口忙
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode());
            }
            if ("others".equals(checkResult)) {//图片不合格,非真人图片
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_PICTURE_ERROR.getErrorCode());
            }
            if ("result_num".equals(checkResult)) {//人脸数异常
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESULTNUM_NOT_1.getErrorCode());
            }
            if ("size".equals(checkResult)) {//人脸太小
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_SIZE_TOO_SMALL.getErrorCode());
            }
            //2020年8月5号 按照需求说明取消活体检测
           /* if ("faceliveness".equals(checkResult)) {//活体值异常
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_FACELIVENESS_TOO_LOW.getErrorCode());
            }*/
            if ("left_eye".equals(checkResult) || "right_eye".equals(checkResult) || "nose".equals(checkResult)
                    || "mouth".equals(checkResult) || "left_cheek".equals(checkResult) || "right_cheek".equals(checkResult)
                    || "chin".equals(checkResult)) {//图片遮挡
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_OCCLUSION.getErrorCode());
            }
            if ("blur".equals(checkResult)) {//模糊
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_BLUR_TOO_LOW.getErrorCode());
            }
            if ("illumination_min".equals(checkResult)) {//光照过暗
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_LOW.getErrorCode());
            }
            if ("illumination_max".equals(checkResult)) {//光照过亮
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_HIGH.getErrorCode());
            }
            if ("pitch".equals(checkResult) || "roll".equals(checkResult) || "yaw".equals(checkResult)) {//角度
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ANGLE_NOT_STRAIGHT.getErrorCode());
            }
            if ("completeness".equals(checkResult)) {//人脸完整度
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_COMPLETENESS_IMPERFECT.getErrorCode());
            }
        }
        String repeatResult = iIotBaiduFaceServiceClient.identifyUser(appCreateBaiduFaceVO);//拿到现有的id
        if (repeatResult != null && !"".equals(repeatResult)) {
            if ("error".equals(repeatResult)) {//调用接口异常
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_IDENTIFY_ERROR.getErrorCode());
            }
            if ("busy".equals(repeatResult)) {//调用接口忙
                return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode());
            }
        }
        String vFaceId = null;
        //判断认证图片是否重复
        if (repeatResult == null) {//人脸库中无此人脸ID使用V_ + pass_id
            appCreateBaiduFaceVO.setUid("V_"+dto.getPassId());
            //创建百度人脸信息
            boolean result = iIotBaiduFaceServiceClient.doCreateBaiduFaceForVisitor(appCreateBaiduFaceVO);
            if (!result) {
                map.put("result","2");
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
            }
            vFaceId = appCreateBaiduFaceVO.getUid();
        }else {//人脸库中有此人脸
            //有此人脸时证明这个人在此项目中注册过人脸业主使用的是这个人的user_id,访客使用的是V_ + pass_id
            //业主不进行重复注册,访客则重新注册(后台有定时任务会定时删除完全无效访客的百度人脸)
            if (repeatResult.substring(0,2).equals("V_")) {//访客人脸则无视还是使用本访客的V_ + pass_id当做人脸编号
                appCreateBaiduFaceVO.setUid(repeatResult);
                //创建百度人脸信息
                boolean result = iIotBaiduFaceServiceClient.doCreateBaiduFaceForVisitor(appCreateBaiduFaceVO);
                if (!result) {
                    map.put("result","2");
                    return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
                }
            }
            vFaceId = repeatResult;
        }
        iAppVisitorPassCodeRecordServiceClient.setVisitPassFace(dto.getPassId(), uploadFilePath, vFaceId, dto.getProjectId(), "", dto.getVisitorReservationMark());

        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        map.put("authDate",formatter.format(currentTime));
        map.put("result","1");
        map.put("uploadFilePath",uploadFilePath);
        //查询当前项目信息
        ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(dto.getProjectId());
        // 平板优先离线，则插入同步数据
        if (projectPO.getOnOffLinePadFace() != null && dto.getVisitorReservationMark()==0) {
            PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
            padFaceSyncDataDTO.setOperateType("3");
            padFaceSyncDataDTO.setProjectId(dto.getProjectId());
            padFaceSyncDataDTO.setPassId(dto.getPassId());
            padFaceSyncDataDTO.setStatus("1");
            padFaceSyncDataDTO.setSourceSystem(1);
            if(projectPO.getOnOffLinePadFace() == 1 ){
                iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
            }
            iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
        }
        return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
    }


    /**
     * <desc>
     *      根据项目编号获取启用状态的楼栋信息
     * </desc>
     * @param projectId 项目编号
     * @return
     * @createDate 2018/11/30
     *  @author Qiang.S
     */
    @RequestMapping(path = "/getBuildList",method = RequestMethod.POST)
    @ResponseBody
    public Object getBuildsInProject(String projectId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(projectId)||StringUtils.isBlank(createTime)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }else if (!projectId.matches("[0-9]{8}")){
                LOG.info("【小程序_我的版块_获取楼栋信息】项目编号非法"+projectId);
                return new MessageVO(MiniProgramErrorCodeEnum.PROJECT_NOT_MATCH.getErrorCode());
            }

            Page<PropertyProjectBuildSimpleInfoVO> page = iAppProjectServiceClient.getBuildsInProject(projectId,"","");
            JSONObject js = new JSONObject();
            js.put("builds",page.getRows());
            messageVO =  new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch (Exception e){
            throw  new DataAccessException("【小程序_我的版块_项目下楼栋信息列表】获取项目下楼栋信息列表失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      根据楼栋ID获取启用状态的单元信息
     * </desc>
     * @param buildId  楼栋ID
     * @return
     * @createDate 2018/11/30
     *  @author Qiang.S
     */
    @RequestMapping(path = "/getUnitList",method = RequestMethod.POST)
    @ResponseBody
    public Object getUnitsInBuild(String buildId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            buildId=request.getAttribute("buildId")==null?null:request.getAttribute("buildId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("buildId",buildId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(buildId)||StringUtils.isBlank(createTime)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            Page<PropertyProjectUnitSimpleInfoVO> page = iAppProjectServiceClient.getUnitsInBuild(buildId);
            JSONObject js = new JSONObject();
            js.put("units",page.getRows());
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch (Exception e){
            throw  new DataAccessException("【小程序_我的版块_楼栋下单元信息列表】获取项目楼栋下单元信息列表失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      根据单元ID获取启用状态的房间信息
     * </desc>
     * @param unitId  单元ID
     * @return
     * @createDate 2018/11/30
     *  @author Qiang.S
     */
    @RequestMapping(path = "/getRoomList",method = RequestMethod.POST)
    @ResponseBody
    public Object getRoomsInUnit(String unitId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            unitId=request.getAttribute("unitId")==null?null:request.getAttribute("unitId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("unitId",unitId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(unitId)||StringUtils.isBlank(createTime)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            Page<PropertyProjectRoomSimpleInfoVO> page = iAppProjectServiceClient.getRoomsInUnit(unitId, "", "");
            JSONObject js = new JSONObject();
            js.put("rooms",page.getRows());
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch (Exception e){
            throw  new DataAccessException("【小程序_我的版块_单元下房间信息列表】获取单元下房间信息列表失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      上传用户通行记录
     * </desc>
     *
     * @param token 用户token
     * @param recordJson json字符串
     * @param createTime 时间戳 验证签名
     * @param sign 签名
     * @return
     * @author Qiang.S
     * @createDate 2018/12/13
     */
    @RequestMapping(path = "/deviceRecord/upload",method = RequestMethod.POST)
    @ResponseBody
    public Object dateRecordlist(String token,String projectId,String recordJson,String createTime,String sign,String imageStr,String imageType){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            recordJson=request.getAttribute("recordJson")==null?null:request.getAttribute("recordJson").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            imageStr=request.getAttribute("imageStr")==null?null:request.getAttribute("imageStr").toString();
            imageType=request.getAttribute("imageType")==null?null:request.getAttribute("imageType").toString();

            Map<String,String> params = new HashMap<>();
            params.put("recordJson",recordJson);
            params.put("createTime",createTime);
            params.put("projectId",projectId);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }

            if(StringUtils.isEmpty(imageStr) && StringUtils.isEmpty(imageType)){
                imageStr="";
                imageType="";
            }

            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(token);
            List<AppUploadPassErrorVO> list=iAppDevicePassRecordServiceClient.uploadRecord(userInfo.getUserId(), projectId, recordJson,imageStr,imageType);
            if(list.isEmpty()) {
                messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }else{
                Map<String,Object> result=new HashMap<>();
                list.forEach(vo->{
                    vo=(AppUploadPassErrorVO)StringHandlerUtil.formatString(vo);
                });
                result.put("failrecordlist",list);
                messageVO=new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode(),result);
            }
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块】上传用户通行记录失败",e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      设置已分享
     * </desc>
     * @param passId  访客编号
     * @return
     * @createDate 2019/04/16
     *  @author Qiang.S
     */
    @LoggerInfo(operateDesc = LogDescConstant.SET_SHARE)
    @RequestMapping(path = "/setShare",method = RequestMethod.POST)
    @ResponseBody
    public Object setShare(String passId,String createTime,String sign){
        MessageVO messageVO;
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            passId=request.getAttribute("passId")==null?null:request.getAttribute("passId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("passId",passId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }else if (StringUtils.isBlank(passId)||StringUtils.isBlank(createTime)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            iAppVisitorPassCodeRecordServiceClient.setShare(passId);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw  new DataAccessException("【小程序_我的版块_设置已分享】设置已分享失败",e);
        }
        return  messageVO;
    }

    /**
     * <desc>
     *      上传图片文件
     * <desc/>
     *
     * @param imageStr 图片二进制
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-07
     */
    private String uploadImageFile(String imageStr,String imageType, FileCatalogEnum fileCatalog){
        try {
            imageStr = URLDecoder.decode(imageStr, "UTF-8");
        }catch (Exception e){
            LOG.info("imageStr URLDecoder失败", e);
            return null;
        }
        byte[] bytes = null;
        try {
            bytes = new BASE64Decoder().decodeBuffer(imageStr);
        } catch (IOException e) {
            LOG.info("BASE64Decoder().decodeBuffer失败,imageStr不合法", e);
            return null;
        }
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );
        try {
            //LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)){
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            }else {
                LOG.info(String.format("图片上传失败，returnCode: %s",returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }

    /**
     * <desc>
     *      上传图片文件
     * <desc/>
     *
     * @param imageType 图片类型
     * @return
     * @author Qiang.S
     * @createDate 2018-05-07
     */
    private String uploadImageFileForByte(byte[] bytes,String imageType, FileCatalogEnum fileCatalog){

        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        UploadFileUtil.UploadFile uploadFileUtil = new UploadFileUtil().new UploadFile(
                FILE_FTP_HOST,
                FILE_FTP_USERNAME,
                FILE_FTP_PASSWORD,
                FILE_FTP_PORT,
                byteArrayInputStream,
                imageType,
                FILE_ACCESS_URL,
                fileCatalog.getType()
        );
        try {
            //LOG.info("正在上传图片");
            Map<String, Object> resultMap = UploadFileUtil.uploadFile(uploadFileUtil);
            //LOG.info("图片上传完毕");
            String returnCode = resultMap.get("returnCode").toString();
            if ("true".equals(returnCode)){
                String fileUrl = resultMap.get("accessPath").toString();
                return fileUrl;
            }else {
                LOG.info(String.format("图片上传失败，returnCode: %s",returnCode));
                return null;
            }
        } catch (IOException e) {
            LOG.info("UploadFileUtil.uploadFile失败", e);
            return null;
        }
    }

    /**
     * <desc>
     *      根据手机号查询房间信息
     * </desc>
     *
     * @param projectId 项目编号
     * @param phoneNum 手机号
     * @return
     * @author Juguang.S
     * @createDate 2019/04/25
     */
    @RequestMapping(value = "/getRoomsInfoByPhone",method = RequestMethod.POST)
    @ResponseBody
    public Object getRoomsInfoByPhone(String phoneNum,String projectId, String createTime, String sign){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            phoneNum=request.getAttribute("phoneNum")==null?null:request.getAttribute("phoneNum").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("phoneNum",phoneNum);
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(phoneNum)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //校验手机号获取userId
            String userId = iPropertyRoomInfoServiceClient.getUserIdByPhone(phoneNum);
            if(StringUtils.isBlank(userId)){
                return new MessageVO(MiniProgramErrorCodeEnum.VISITOR_PHONE_CHECK_NOTPASS.getErrorCode());
            }
            List<MiniProgramPassRoomListVO> list = iPropertyRoomInfoServiceClient.myRoomsInfo(userId,projectId);
            if(list == null || list.isEmpty()){
                return new MessageVO(MiniProgramErrorCodeEnum.VISITOR_PHONE_CHECK_NOTPASS.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),list);
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的板块】根据手机号查询房间信息失败",e);
        }
    }

    /**
     * <desc>
     *      业主访客单审批
     * </desc>
     * @param passId 访客单ID
     * @param checkStatus 物业审核状态 1代表审批通过 2代表审批拒绝
     * @param projectId 项目编号
     * @return
     * @author JuGuang.S
     * @createDate 2019/04/28
     */
    @ResponseBody
    @PostMapping(path = "checkVisitor")
    @LoggerInfo(operateDesc = LogDescConstant.OWNER_CHECK_VISITOR_DESC)
    public Object propertyCheckVisitor(String token,String passId,Integer checkStatus,String projectId,String createTime, String sign, String visitorTime){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            passId=request.getAttribute("passId")==null?null:request.getAttribute("passId").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            checkStatus=request.getAttribute("checkStatus")==null?null:Integer.valueOf(request.getAttribute("checkStatus").toString());
            visitorTime = request.getAttribute("visitorTime") == null ? null : request.getAttribute("visitorTime").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("passId",passId);
            params.put("checkStatus",checkStatus.toString());
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            params.put("visitorTime",visitorTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(passId) || StringUtils.isBlank(checkStatus.toString())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //此处需要判断项目是否配置物业是否需要审批
            PropertyGetVisitorInfoVO infoVO = iPropertyVisitorServiceClient.getVisitorInfo(passId);
            //以下传参的项目编号不用前端所传的，需用根据passId所查的
            OperateProjectDetailVO operateProjectDetailVO = iOperateProjectServiceClient.getDetail(infoVO.getProjectId());
            if(iPropertyVisitorServiceClient.propertyCheckVisitor(passId,checkStatus,UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY),1)>0){
                WeChatVisitorMsgDTO msgDTO = new WeChatVisitorMsgDTO();
                if(checkStatus==1 && operateProjectDetailVO.getMiniVisitorProperty()==0){

                    //审批时拜访时间发生变化后，需重新处理二维码相关逻辑
                    AppVisitorPassCodeRecordPO recordPO = iPropertyVisitorServiceClient.getVisitorByRenewVisitor(passId);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String startStr = String.format("%s%s",visitorTime," 00:00:00");
                    if(!dateFormat.format(recordPO.getStartTime()).equals(startStr)){
                        AppGetVisitPassWordDTO appGetVisitPassWordDTO = new AppGetVisitPassWordDTO();
                        appGetVisitPassWordDTO.setPassId(passId);
                        appGetVisitPassWordDTO.setVisitTime(visitorTime);
                        appGetVisitPassWordDTO.setDeviceUniques(recordPO.getTemporaryAuthDeviceUniques());
                        appGetVisitPassWordDTO.setRoomId(recordPO.getRoomId());
                        appGetVisitPassWordDTO.setProjectId(projectId);
                        appGetVisitPassWordDTO.setIntervieweePhone(recordPO.getIntervieweePhone());
                        iAppVisitorPassCodeRecordServiceClient.updateQrcodeByTimeModify(appGetVisitPassWordDTO);
                    }

                    msgDTO.setOperateType(VisitorOperateTypeEnum.NO_PROPERTY_CHECK.getType().toString());

                    // 平板优先离线且只需要业主审核无需物业审核则插入同步数据
                    if (operateProjectDetailVO.getOnOffLinePadFace() != null) {
                        //LOG.info("【业主审批物业不需审批后向C#人脸识别系统下发增量数据】passId："+ passId + "projectId:"+projectId);
                        PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                        padFaceSyncDataDTO.setOperateType("3");
                        padFaceSyncDataDTO.setProjectId(infoVO.getProjectId());
                        padFaceSyncDataDTO.setPassId(passId);
                        padFaceSyncDataDTO.setStatus("1");
                        padFaceSyncDataDTO.setSourceSystem(1);
                        if(operateProjectDetailVO.getOnOffLinePadFace() == 1){
                            iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
                        }
                        iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
                    }
                }else if(checkStatus==1 && operateProjectDetailVO.getMiniVisitorProperty()==1){
                    msgDTO.setOperateType(VisitorOperateTypeEnum.NEED_PROPERTY_CHECK.getType().toString());

                    //审批时拜访时间发生变化后，需重新处理二维码相关逻辑
                    AppVisitorPassCodeRecordPO recordPO = iPropertyVisitorServiceClient.getVisitorByRenewVisitor(passId);
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    String startStr = String.format("%s%s",visitorTime," 00:00:00");
                    if(!dateFormat.format(recordPO.getStartTime()).equals(startStr)){
                        AppGetVisitPassWordDTO appGetVisitPassWordDTO = new AppGetVisitPassWordDTO();
                        appGetVisitPassWordDTO.setPassId(passId);
                        appGetVisitPassWordDTO.setVisitTime(visitorTime);
                        appGetVisitPassWordDTO.setDeviceUniques(recordPO.getTemporaryAuthDeviceUniques());
                        appGetVisitPassWordDTO.setRoomId(recordPO.getRoomId());
                        appGetVisitPassWordDTO.setProjectId(projectId);
                        appGetVisitPassWordDTO.setIntervieweePhone(recordPO.getIntervieweePhone());
                        iAppVisitorPassCodeRecordServiceClient.updateQrcodeByTimeModify(appGetVisitPassWordDTO);
                    }
                } else{
                    msgDTO.setOperateType(VisitorOperateTypeEnum.CHECK_REFUSE.getType().toString());
                }
                msgDTO.setPassId(passId);
                iWeChatTemplateMsgServiceClient.sendWeChatTemplateMsg(msgDTO);
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.ERROR.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【小程序_业主访客单审核】业主访客单审核失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目小程序审批配置
     * </desc>
     * @param projectId 项目编号
     * @return
     * @author JuGuang.S
     * @createDate 2019/04/28
     */
    @ResponseBody
    @UnAuthAccessRequired
    @PostMapping(path = "getMiniCheckByProjectId")
    public Object getMiniCheckByProjectId(String projectId,String createTime, String sign){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            OperateProjectDetailVO operateProjectDetailVO = iOperateProjectServiceClient.getDetail(projectId);
            Map<String,String> map = new HashMap<>();
            map.put("miniVisitorOwner",operateProjectDetailVO.getMiniVisitorOwner().toString());
            map.put("miniVisitorProperty",operateProjectDetailVO.getMiniVisitorProperty().toString());
            map.put("isFaceRecognition",operateProjectDetailVO.getIsFaceRecognition().toString());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
        }catch (Exception e){
            throw new DataAccessException("【小程序_获取项目小程序审批配置】获取项目小程序审批配置失败", e);
        }
    }

    /**
     * <desc>
     *      访客预约凭证列表（业主身份+访客身份）
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return 格式化响应结果
     * @author Juguang.S
     * @createDate 2019/04/29
     */
    @ResponseBody
    @PostMapping("/getReservationProofPage")
    public Object getReservationProofPage(MiniGetReservationProofPageDTO dto, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto=HttpProtocolUtil.parseRequestParamToDTO(MiniGetReservationProofPageDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("currentPage",dto.getCurrentPage());
            params.put("pageSize",dto.getPageSize());
            params.put("checkStatus",dto.getCheckStatus());
            params.put("type",dto.getType());
            params.put("createTime",dto.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(dto.getCheckStatus()) || StringUtils.isEmpty(dto.getType())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(dto.getToken(), MINI_PROGRAM_USER_TOKEN_KEY);
            dto.setLoginUserId(userId);
            Page<MiniGetReservationProofPageVO> page = iAppVisitorPassCodeRecordServiceClient.getReservationProofPage(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_访客通行】获取访客预约凭证列表失败",e);
        }
    }

    /**
     * <desc>
     *      获取访客身份通行记录
     * </desc>
     *
     * @param dto 接收数据dto类
     * @param sign 签名
     * @return 格式化响应结果
     * @author Juguang.S
     * @createDate 2019/04/30
     */
    @ResponseBody
    @PostMapping("/getVisitorPassRecordPage")
    public Object getVisitorPassRecordPage(MiniGetReservationProofPageDTO dto, String sign) {
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            dto=HttpProtocolUtil.parseRequestParamToDTO(MiniGetReservationProofPageDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String, String> params = new HashMap<>();
            params.put("currentPage", dto.getCurrentPage());
            params.put("pageSize", dto.getPageSize());
            params.put("createTime",dto.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }

            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(dto.getToken(), MINI_PROGRAM_USER_TOKEN_KEY);
            dto.setLoginUserId(userId);
            Page<MiniGetVisitorPassRecordPageVO> page = iAppVisitorPassCodeRecordServiceClient.getVisitorPassRecordPage(dto);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), page);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_访客通行】获取访客身份通行记录列表失败", e);
        }
    }

     /**
     * <desc>
     *      获取访客单信息(主动申请)
     * </desc>
     *
     * @param sign 签名
     * @return 格式化响应结果
     * @author Qiang.S
     * @createDate 2019/05/05
     */
    @ResponseBody
    @PostMapping("/getReservationVisitorInfo")
    public Object getReservationVisitorInfo(String token,String projectId, String createTime, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), iAppVisitorPassCodeRecordServiceClient.getReservationVisitorInfo(userId,projectId));
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块_获取访客单信息】获取访客单信息失败",e);
        }
    }

    /**
     * <desc>
     *      获取当前用户注册人脸信息
     * </desc>
     *
     * @param sign 签名
     * @return 格式化响应结果
     * @author Juguang.S
     * @createDate 2019/05/06
     */
    @ResponseBody
    @PostMapping("/getUserFaceUrlInfo")
    public Object getUserFaceUrlInfo(String token,String projectId, String createTime, String sign,String type){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            type=request.getAttribute("type")==null?null:request.getAttribute("type").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("type",type);
            params.put("createTime",createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(type)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            //解密拿到userId
            String userId = UserTokenUtil.tokenDecrypt(token, MINI_PROGRAM_USER_TOKEN_KEY);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iAppVisitorPassCodeRecordServiceClient.getUserFaceUrlInfo(userId,projectId,type));
        } catch (Exception e) {
            throw new DataAccessException("【小程序_获取当前用户注册人脸信息】获取当前用户注册人脸信息失败",e);
        }
    }

    /**
     * <desc>
     *      上传常用楼层
     * </desc>
     *
     * @param projectId 项目编号
     * @param deviceUnique 设备序列号
     * @param loadDeviceOrder 常用楼层名称
     * @param  loadPublicOrder  常用公共楼层名称
     * @return 标准格式化响应结果
     * @author wangzhi
     * @createDate 2019/10/08
     */
    @ResponseBody
    @PostMapping(path = "uploadChoiceFloor")
    @LoggerInfo(operateDesc = LogDescConstant.UPLOAD_CHOICE_FLOOR_DESC)
    public Object uploadChoiceFloor(String projectId, String deviceUnique, String loadDeviceOrder,String loadPublicOrder, String token, String createTime, String sign) {
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            loadDeviceOrder = request.getAttribute("loadDeviceOrder") == null ? "" : request.getAttribute("loadDeviceOrder").toString();
            loadPublicOrder = request.getAttribute("loadPublicOrder") == null ? "" : request.getAttribute("loadPublicOrder").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
            sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
            //验签
            Map<String, String> params = new HashMap<>();
            params.put("projectId", projectId);
            params.put("deviceUnique", deviceUnique);
            params.put("loadDeviceOrder", loadDeviceOrder);
            params.put("loadPublicOrder", loadPublicOrder);
            params.put("createTime", createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId) || StringUtils.isBlank(deviceUnique) || StringUtils.isBlank(token)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            // 从缓存中获取用户信息
            AppUserCacheVO userInfo = userCache.retrieve(token);
            iAppProjectServiceClient.uploadChoiceFloor(projectId, deviceUnique, loadDeviceOrder, userInfo.getUserId(),loadPublicOrder);
            //组装云对讲同步指令
            List<DeviceBusinessChangeLogPO> changeLogPOS = new ArrayList<>();
            JSONObject json = new JSONObject();
            json.put("userId", userInfo.getUserId());
            json.put("projectId", projectId);
            DeviceBusinessChangeLogPO deviceBusinessChangeLogPO =
                    new DeviceBusinessChangeLogPO(SmartCommunityEnum.PUSH_USER_PROJECT, json,projectId);
            changeLogPOS.add(deviceBusinessChangeLogPO);
            JSONObject dataJs = new JSONObject();
            dataJs.put("data",changeLogPOS);
            //发送云对讲指令
            messageSender.send(
                    RabbitMQConstant.RABBITMQ_HANDLE_SMART_COMMUNITY_ORDERS_QUEUE,
                    JSON.toJSONString(dataJs),
                    RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_SMART_COMMUNITY_ORDERS_ROUTING_KEY
            );
            //发送平板指令
            //推送平板增量数据
            List<Map<String,Object>> padDatas = iPropertyHouseHoldInfoServiceClient.getUserRoomIdsByUserIdAndProjectId(
                    StringHandlerUtil.splitString(userInfo.getUserId()),projectId
            );
            //发送平板指令
            List<PadUserAuthPushDTO> dtos = new ArrayList<>();
            Map<String,Object> padMessage = new HashMap<>();
            for(Map<String,Object>  padData : padDatas){
                PadUserAuthPushDTO dto = new PadUserAuthPushDTO();
                dto.setProjectId(projectId);
                dto.setRoomId(padData.get("roomId").toString());
                dto.setUserId(padData.get("userId").toString());
                dto.setPushType(PadChangeBusinessEnum.PUSH_USER.getCommandType());
                //修改App用户信息接口
                dto.setInstructionType(15);
                dto.setSourceSystem(2);
                dtos.add(dto);
            }

            padMessage.put("data",JsonUtil.toJSON(dtos));
            messageSender.send(RabbitMQConstant.RABBITMQ_PAD_USER_AUTH_CHANGE_PUSH_QUEUE,
                    JsonUtil.toJSON(padMessage), RabbitMQConstant.RABBITMQ_EQUIP_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_PAD_USER_AUTH_CHANGE_PUSH_KEY);

            /**
             * 2021年3月16日变更，CloudEntranceChangeBusinessEnum.PUSH_USER_PROJECT的commandType为6，SmartCommunityEnum.
             * PUSH_USER_PROJECT的commandType为2，当发送云门禁指令为2时，云门禁指令消费端会处理成另一套逻辑，所以由如下变
             * 更，即重新组装指令，更换commandType为6 后再发送指令
             *
             * @author zhuyajun
             * @createDate  2021/3/16
             */
            List<DeviceBusinessEntranceChangeLogPO> entranceChangeLogPOS = new ArrayList<>();
            entranceChangeLogPOS.add(new DeviceBusinessEntranceChangeLogPO(CloudEntranceChangeBusinessEnum.PUSH_USER_PROJECT, json,projectId));
            JSONObject entranceDataJs = new JSONObject();
            entranceDataJs.put("data", entranceChangeLogPOS);
            //发送云门禁指令
            messageSender.send(
                    RabbitMQConstant.RABBITMQ_HANDLE_CLOUD_ENTRANCE_CHANGE_BUSINESS_QUEUE,
                    JSON.toJSONString(entranceDataJs),
                    RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_EXCHANGE,
                    RabbitMQConstant.RABBITMQ_CLOUD_ENTRANCE_CHANGE_BUSINESS_ROUTING_KEY
            );
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        } catch (Exception e) {
            throw new DataAccessException("【小程序_上传常用楼层】上传常用楼层失败", e);
        }
    }

    /**
     * <desc>
     *      获取项目的banner广告信息 小程序
     * <desc/>
     *
     * @param projectId 项目id
     * @param sign 签名
     * @return
     * @author Juguang.S
     * @createDate 2019/08/28
     */
    @RequestMapping(value = "/getBanner",method = RequestMethod.POST)
    @ResponseBody
    public Object getBanner(String projectId,String createTime, String sign){
        try {
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验证签名
            Map<String,String> params = new HashMap<>();
            params.put("projectId",projectId);
            params.put("createTime",createTime);
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId)){
                return  new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }

            List<OperateAdImgVO> adImgVOS = iOperateAdManageServiceClient.getBannerImgs(projectId, 1,2);

            //处理null值
            if (adImgVOS != null && adImgVOS.size()>0) {
                for (OperateAdImgVO img: adImgVOS){
                    StringHandlerUtil.formatString(img);
                }
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), adImgVOS);
        }catch (Exception e){
            throw new DataAccessException("【小程序2.0】获取服务页面Banner失败", e);
        }
    }

    /**
     * <desc>
     *      百度人脸注册。
     * <desc/>
     *
     * @param appCreateBaiduFaceDTO 人脸注册信息DTO实体类
     * @return
     * @author Juguang.S
     * @createDate 2019/08/29
     */
    @LoggerInfo(operateDesc = LogDescConstant.APP_CREATE_BAIDUFACE)
    @RequestMapping(path ="/createBaiduFace",method = RequestMethod.POST)
    @ResponseBody
    public Object createBaiduFace(AppCreateBaiduFaceDTO appCreateBaiduFaceDTO, String sign) {
        MessageVO messageVO;
        try {
            //验证签名
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            appCreateBaiduFaceDTO=HttpProtocolUtil.parseRequestParamToDTO(AppCreateBaiduFaceDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();

            Map<String,String> params = new HashMap<>();
            params.put("createTime",appCreateBaiduFaceDTO.getCreateTime());
            params.put("imageStr",appCreateBaiduFaceDTO.getImageStr());
            params.put("imageType",appCreateBaiduFaceDTO.getImageType());
            params.put("projectId",appCreateBaiduFaceDTO.getProjectId());
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            //判断必要信息是否为空
            if(StringUtils.isEmpty(appCreateBaiduFaceDTO.getToken()) || StringUtils.isEmpty(appCreateBaiduFaceDTO.getProjectId())
                    || StringUtils.isEmpty(appCreateBaiduFaceDTO.getImageStr())){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=(AppUserCacheVO)StringHandlerUtil.formatString(userCache.retrieve(appCreateBaiduFaceDTO.getToken()));
            if(null == userInfo){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //判断项目是否开启人脸识别,并查询是否有百度库key
            OperateFaceApplyInfoVO operateFaceApplyInfoVO = iOperateFaceApplyServiceClient.getFaceByProjectId(appCreateBaiduFaceDTO.getProjectId());
            if(operateFaceApplyInfoVO == null){
                ErrorCode errorCode = AppErrorCodeEnum.PROJECT_FACE_APPID_INEXISTENCE.getErrorCode();
                return new MessageVO(errorCode);
            }
            AppCreateBaiduFaceVO appCreateBaiduFaceVO = new AppCreateBaiduFaceVO();
            appCreateBaiduFaceVO.setProjectId(appCreateBaiduFaceDTO.getProjectId());
            appCreateBaiduFaceVO.setUserPhone(userInfo.getPhoneNo());
            appCreateBaiduFaceVO.setUid(userInfo.getUserId());
            appCreateBaiduFaceVO.setUserName(userInfo.getUserName());
            appCreateBaiduFaceVO.setUserInfo(userInfo.getUserName());//userInfo使用用户名
            appCreateBaiduFaceVO.setAPP_ID(operateFaceApplyInfoVO.getAppId());
            appCreateBaiduFaceVO.setAPI_KEY(operateFaceApplyInfoVO.getApiKey());
            appCreateBaiduFaceVO.setSECRET_KEY(operateFaceApplyInfoVO.getSecretKey());
            appCreateBaiduFaceVO.setFaceScore(operateFaceApplyInfoVO.getFaceScore()==0F?80F:operateFaceApplyInfoVO.getFaceScore());
            String uploadFilePath = uploadImageFile(appCreateBaiduFaceDTO.getImageStr(), appCreateBaiduFaceDTO.getImageType(), FileCatalogEnum.BAIDU_FACE_CREATE_FILE);
            appCreateBaiduFaceVO.setImageUrl(uploadFilePath);
            appCreateBaiduFaceVO.setUploadFilePath(uploadFilePath);

            String checkResult = iIotBaiduFaceServiceClient.faceVerify(appCreateBaiduFaceVO);
            if (checkResult != null && !"".equals(checkResult)) {
                if ("error".equals(checkResult)) {//调用接口异常
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACEVERFY_ERROR.getErrorCode());
                }
                if ("busy".equals(checkResult)) {//调用接口忙
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode());
                }
                if ("others".equals(checkResult)) {//图片不合格,非真人图片
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_PICTURE_ERROR.getErrorCode());
                }
                if ("result_num".equals(checkResult)) {//人脸数异常
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_RESULTNUM_NOT_1.getErrorCode());
                }
                if ("size".equals(checkResult)) {//人脸太小
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_SIZE_TOO_SMALL.getErrorCode());
                }
                //2020年8月5号 按照需求说明取消活体检测
               /* if ("faceliveness".equals(checkResult)) {//活体值异常
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_FACELIVENESS_TOO_LOW.getErrorCode());
                }*/
                if ("left_eye".equals(checkResult) || "right_eye".equals(checkResult) || "nose".equals(checkResult)
                        || "mouth".equals(checkResult) || "left_cheek".equals(checkResult) || "right_cheek".equals(checkResult)
                        || "chin".equals(checkResult)) {//图片遮挡
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_OCCLUSION.getErrorCode());
                }
                if ("blur".equals(checkResult)) {//模糊
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_BLUR_TOO_LOW.getErrorCode());
                }
                if ("illumination_min".equals(checkResult)) {//光照过暗
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_LOW.getErrorCode());
                }
                if ("illumination_max".equals(checkResult)) {//光照过亮
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ILLUMINATION_TOO_HIGH.getErrorCode());
                }
                if ("pitch".equals(checkResult) || "roll".equals(checkResult) || "yaw".equals(checkResult)) {//角度
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_ANGLE_NOT_STRAIGHT.getErrorCode());
                }
                if ("completeness".equals(checkResult)) {//人脸完整度
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_FACE_COMPLETENESS_IMPERFECT.getErrorCode());
                }
            }
            //  2020年8月5号 按照需求说明取消人脸重复比对
         /*   String repeatResult = iIotBaiduFaceServiceClient.identifyUser(appCreateBaiduFaceVO);//拿到现有的id
            if (repeatResult != null && !"".equals(repeatResult)) {
                if ("error".equals(repeatResult)) {//调用接口异常
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_IDENTIFY_ERROR.getErrorCode());
                }
                if ("busy".equals(repeatResult)) {//调用接口忙
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_BAIDU_BUSY.getErrorCode());
                }
                if ("face_repeat".equals(repeatResult)) {//人脸重复注册
                    return new MessageVO(PropertyErrorCodeEnum.APPUSER_CREATE_FACE_REPEAT.getErrorCode());
                }
            }*/

            boolean result = iIotBaiduFaceServiceClient.createBaiduFace(appCreateBaiduFaceVO);
            Map<String, String> map = new HashMap<>();
            if (!result) {
                map.put("result","2");
                return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
            }
            Date currentTime = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            map.put("authDate",formatter.format(currentTime));
            map.put("result","1");
            map.put("uploadFilePath",uploadFilePath);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),map);
            //查询当前项目信息
            ProjectPO projectPO = iOperateProjectServiceClient.getOneProject(appCreateBaiduFaceDTO.getProjectId());
            // 平板优先离线，则插入同步数据
            if (projectPO.getOnOffLinePadFace() != null) {
                PadFaceSyncDataDTO padFaceSyncDataDTO = new PadFaceSyncDataDTO();
                padFaceSyncDataDTO.setOperateType("1");
                padFaceSyncDataDTO.setAppUserIds(userInfo.getUserId());
                padFaceSyncDataDTO.setProjectId(appCreateBaiduFaceDTO.getProjectId());
                padFaceSyncDataDTO.setStatus("1");
                padFaceSyncDataDTO.setSourceSystem(1);
                if(projectPO.getOnOffLinePadFace() == 1){
                    iPadFaceSyncDataServiceClient.userOrFloorSync(padFaceSyncDataDTO);
                }
                iPadFaceSyncDataServiceClient.userOrFloorSyncSmartCard(padFaceSyncDataDTO);
            }
        } catch (Exception e) {
            throw new DataAccessException("【小程序2.0】人脸认证申请失败", e);
        }
        return messageVO;
    }

    /**
     * <desc>
     *      获取当前用户临时权限设备列表
     * </desc>
     *
     * @param token
     * @param createTime 时间戳参与签名
     * @return
     * @author Juguang.S
     * @createDate 2019/09/02
     */
    @RequestMapping(value = "/getVisitorDeviceList",method = RequestMethod.POST)
    @ResponseBody
    public Object getUserTemporaryAuthDeviceList(String token,String createTime,String sign,String projectId){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("projectId",projectId);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(token);

            //获取当前用户临时权限
            List<AppUserDevicesVO> deviceList = iAppDeviceServiceClient.getUserDevicesInfo(userInfo.getUserId(), projectId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),deviceList);
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的版块】添加访客获取用户临时权限设备列表失败",e);
        }

    }

    /**
     * <desc>
     *      创建访客时创建或修改标签
     * </desc>
     *
     * @param deviceMarkDTO 创建或修改标签的信息
     * @return
     * @author Juguang.S
     * @createDate 2019/09/02
     */
    @ResponseBody
    @LoggerInfo(operateDesc = LogDescConstant.CREATE_OR_UPDATE_DEVEICE_MARKS_INFO)
    @RequestMapping(value = "/createDeviceMark",method = RequestMethod.POST)
    public Object createDeviceMark(CreateDeviceMarkDTO deviceMarkDTO,String sign){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            deviceMarkDTO=HttpProtocolUtil.parseRequestParamToDTO(CreateDeviceMarkDTO.class,request);
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",deviceMarkDTO.getCreateTime());
            params.put("projectId",deviceMarkDTO.getProjectId());
            params.put("markId",deviceMarkDTO.getMarkId());
            params.put("markName",deviceMarkDTO.getMarkName());
            params.put("deviceUniques",deviceMarkDTO.getDeviceUniques());
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(deviceMarkDTO.getToken());
            deviceMarkDTO.setLoginUserId(userInfo.getUserId());
            iAppDeviceServiceClient.saveOrUpdateDeviceMark(deviceMarkDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的版块】创建访客时创建或修改标签失败",e);
        }
    }

    /**
     * <desc>
     *      获取当前用户的设备标签
     * </desc>
     *
     * @param token
     * @param createTime 时间戳参与签名
     * @return
     * @author Juguang.S
     * @createDate 2019/09/02
     */
    @ResponseBody
    @RequestMapping(value = "/getDeviceMark",method = RequestMethod.POST)
    public Object getDeviceMark(String token,String createTime,String sign,String projectId){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("projectId",projectId);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(token);
            List<VisitorDeviceMarkInfoVO> markList= iAppDeviceServiceClient.getDeviceMark(userInfo.getUserId(),projectId);
            JSONObject js = new JSONObject();
            js.put("markAry",markList);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),js);
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的版块】获取当前用户的设备标签失败",e);
        }
    }

    /**
     * <desc>
     *      删除设备标签
     * </desc>
     *
     * @param token
     * @param projectId 项目编号
     * @param markId 标签ID
     * @return
     * @author Juguang.S
     * @createDate 2019/09/03
     */
    @ResponseBody
    @RequestMapping(value = "/deleteDeviceMark",method = RequestMethod.POST)
    @LoggerInfo(operateDesc = LogDescConstant.DELETE_DEVEICE_MARKS_INFO)
    public Object deleteDeviceMark(String token,String createTime,String sign,String projectId,String markId){
        try{
            HttpServletRequest request= ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token=request.getAttribute("token")==null?null:request.getAttribute("token").toString();
            createTime=request.getAttribute("createTime")==null?null:request.getAttribute("createTime").toString();
            sign=request.getAttribute("sign")==null?null:request.getAttribute("sign").toString();
            projectId=request.getAttribute("projectId")==null?null:request.getAttribute("projectId").toString();
            markId=request.getAttribute("markId")==null?null:request.getAttribute("markId").toString();
            //验签
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("projectId",projectId);
            params.put("markId",markId);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if(StringUtils.isEmpty(projectId) || StringUtils.isEmpty(markId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            iAppDeviceServiceClient.deleteDeviceMark(markId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch ( Exception e){
            throw new DataAccessException("【小程序_我的版块】删除设备标签失败",e);
        }
    }

    /**
     * <desc>
     *      获取小程序功能配置
     * </desc>
     *
     * @param projectId 项目id
     * @param token
     * @param createTime
     * @param sign
     * @return
     * @Author Zhu.yj
     * @createDate  2020/3/26
     */
    @RequestMapping(value = "/getMiniConfig",method = RequestMethod.POST)
    public Object getMiniConfig(String projectId, String token,String createTime,String sign,HttpServletRequest request){
        try {
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
            sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
            Map<String,String> params = new HashMap<>();
            params.put("createTime",createTime);
            params.put("projectId",projectId);
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            List<MiniProgramFunctionInfoPO> miniProgramFunctionInfoPOS = iOperateMiniProgramFunctionServiceClient.getMiniConfig(projectId);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),miniProgramFunctionInfoPOS);
        }catch (Exception e){
            throw new DataAccessException("【小程序-我的-获取小程序功能配置getMiniConfig】获取小程序功能配置失败",e);
        }
    }

    /**
     * <desc>
     *      获取访客时间限制信息
     * </desc>
     *
     * @param projectId 项目编号
     * @return
     * @author Juguang.S
     * @createDate 2019/09/15
     */
    @ResponseBody
    @RequestMapping(value = "/getVisitorTimeInfo",method = RequestMethod.POST)
    public Object getVisitorTimeInfo(String projectId){
        try{
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
            if(StringUtils.isEmpty(projectId)){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(),iPropertyVisitorServiceClient.getVisitorTimeInfo(projectId));
        }catch ( Exception e){
            throw new DataAccessException("【小程序_访客管理】获取访客时间限制信息失败",e);
        }
    }


    /**
     * <desc>
     *      获取用户无接触二维码
     * </desc>
     *
     * @param deviceUnique 项目id
     * @param logicalFloor 楼层名称
     * @param createTime 时间戳 验证签名
     * @param sign 签名
     * @return
     * @author Qiang.S
     * @createDate 2017/11/15
     */
    @RequestMapping(path = "/getNoTouchQRCode",method = RequestMethod.POST)
    @ResponseBody
    public Object getNoTouchQRCode(String token,String deviceUnique,String logicalFloor,String createTime,String sign,String language) {
        MessageVO messageVO;
        try {
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
            deviceUnique = request.getAttribute("deviceUnique") == null ? null : request.getAttribute("deviceUnique").toString();
            logicalFloor = request.getAttribute("logicalFloor") == null ? null : request.getAttribute("logicalFloor").toString();
            createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
            sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
            Map<String, String> params = new HashMap<>();
            params.put("deviceUnique", deviceUnique);
            params.put("logicalFloor", logicalFloor);
            params.put("createTime", createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }
            if (StringUtils.isBlank(deviceUnique) || StringUtils.isBlank(logicalFloor)) {
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            //从缓存中获取用户信息
            AppUserCacheVO userInfo=userCache.retrieve(token);

            String noTouchQRCode = iAppDeviceServiceClient.getNoTouchQRCode(userInfo.getUserId(), deviceUnique, logicalFloor);
            Map<String, String> data = new HashMap<>();
            data.put("endTime", "");
            data.put("endTimeHint", "1");
            data.put("qrcode", noTouchQRCode);
            messageVO = new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【小程序_我的版块】获取用户无接触二维码失败", e);
        }
        return messageVO;
    }


    /**
     * <desc>
     *     访客详情
     * </desc>
     *
     * @param
     * @return
     * @author caoshuai
     * @createDate 2021/1/21 15:47
     */
    @ResponseBody
    @PostMapping("/getVisitorsInfo")
    public Object getVisitorsInfo(String projectId, String token, String sign, String passId,String createTime){
        try {
            boolean flag1 = StringUtils.isNotBlank(projectId) || StringUtils.isNotBlank(token) || StringUtils.isNotBlank(sign);
            if (!flag1) {
                HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
                token = request.getAttribute("token") == null ? null : request.getAttribute("token").toString();
                projectId = request.getAttribute("projectId") == null ? null : request.getAttribute("projectId").toString();
                sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
                passId = request.getAttribute("passId") == null ? null : request.getAttribute("passId").toString();
                createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
            }
            //验签
            Map<String, String> params = new HashMap<>();
            params.put("projectId", projectId);
            params.put("passId", passId);
            params.put("createTime", createTime);
            //验证签名
            if(!Md5EncryptUtil.checkAppSignValue(params,sign,MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)){
                return  new MessageVO(MiniProgramErrorCodeEnum.MINI_PROGRAM_SIGN_ERR.getErrorCode());
            }

            Map<String, Object> data = iAppDevicePassRecordServiceClient.getVisitorsInfo(passId);

            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), data);
        } catch (Exception e) {
            throw new DataAccessException("【APP_我的版块】获取访客通行密码邀请记录失败", e);
        }
    }


    /**
     * <desc>
     *      获取区项目信息列表
     * </desc>
     *
     * @param
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/8
     */
    @PostMapping("/getDistrictProject")
    public Object getDistrictProject(AppGetProjectDTO appGetProjectDTO, HttpServletRequest request){
        try{
            appGetProjectDTO = HttpProtocolUtil.parseRequestParamToDTO(AppGetProjectDTO.class, request);
            Map<String, String> params = new HashMap<>();
            params.put("cityId", appGetProjectDTO.getCityId());
            params.put("createTime", appGetProjectDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, appGetProjectDTO.getSign(), MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            List<AppDistinctProjectVO> distinctProjectVOList =  iAppProjectServiceClient.getProjectsInCity(appGetProjectDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), distinctProjectVOList);
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块】获取区项目列表失败", e);
        }
    }

    /**
     * <desc>
     *      保存项目
     * </desc>
     *
     * @param appGetProjectDTO app获取参数DTO
     * @param request
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/8
     */
    @PostMapping("saveProject")
    public Object saveProject(AppGetProjectDTO appGetProjectDTO, HttpServletRequest request){
        try{
            appGetProjectDTO = HttpProtocolUtil.parseRequestParamToDTO(AppGetProjectDTO.class, request);
            Map<String, String> params = new HashMap<>();
            params.put("projectId", appGetProjectDTO.getProjectId());
            params.put("createTime", appGetProjectDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, appGetProjectDTO.getSign(), MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            AppUserCacheVO userCacheVO = userCache.retrieve(appGetProjectDTO.getToken());
            appGetProjectDTO.setUserId(userCacheVO.getUserId());
            appGetProjectDTO.setPhoneNum(userCacheVO.getPhoneNo());
            iAppProjectServiceClient.saveUserProject(appGetProjectDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的版块】保存项目失败", e);
        }
    }

    /**
     * <desc>
     *      删除项目
     * </desc>
     *
     * @param appGetProjectDTO 删除项目参数DTO
     * @param request
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/8
     */
    @PostMapping("deleteProject")
    public Object deleteProject(AppGetProjectDTO appGetProjectDTO, HttpServletRequest request){
        try{
            appGetProjectDTO = HttpProtocolUtil.parseRequestParamToDTO(AppGetProjectDTO.class, request);
            Map<String, String> params = new HashMap<>();
            params.put("projectId", appGetProjectDTO.getProjectId());
            params.put("createTime", appGetProjectDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, appGetProjectDTO.getSign(), MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            AppUserCacheVO userCacheVO = userCache.retrieve(appGetProjectDTO.getToken());
            appGetProjectDTO.setUserId(userCacheVO.getUserId());
            iAppProjectServiceClient.deleteUserProject(appGetProjectDTO);
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode());
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的板块deleteProject】删除项目失败", e);
        }
    }

    /**
     * <desc>
     *      社区园区搜索
     * </desc>
     *
     * @param appGetProjectDTO 项目搜索传参DTO
     * @return
     * @Author Zhu.yj
     * @createDate  2021/4/6
     */
    @RequestMapping(value = "communitySearch", method = RequestMethod.POST)
    public Object communitySearch(AppGetProjectDTO appGetProjectDTO, HttpServletRequest request){
        try {
            appGetProjectDTO = HttpProtocolUtil.parseRequestParamToDTO(AppGetProjectDTO.class, request);
            Map<String, String> params = new HashMap<>();
            params.put("projectName", appGetProjectDTO.getProjectName());
            params.put("createTime", appGetProjectDTO.getCreateTime());
            if (!Md5EncryptUtil.checkAppSignValue(params, appGetProjectDTO.getSign(), MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            List<Map<String, Object>> projectList = iAppProjectServiceClient.getProjectByProjectName(appGetProjectDTO.getProjectName());
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), projectList);
        }catch (Exception e){
            throw new DataAccessException("【小程序_我的板块communitySearch】搜索项目失败", e);
        }
    }

    /**
     * <desc>
     *      送检非标-获取访客二维码内容
     * </desc>
     *
     * @param visitorId
     * @return
     * @Author Zhu.yj
     * @createDate  2021/6/2
     */
    @UnAuthAccessRequired
    @PostMapping("/getQRCodeContent")
    public Object getQRCodeContent(String visitorId, String createTime, String sign, HttpServletRequest request){
        try{
            visitorId = request.getAttribute("visitorId") == null ? null : request.getAttribute("visitorId").toString();
            createTime = request.getAttribute("createTime") == null ? null : request.getAttribute("createTime").toString();
            sign = request.getAttribute("sign") == null ? null : request.getAttribute("sign").toString();
            if (visitorId == null || createTime == null){
                return new MessageVO(BaseErrorCodeEnum.NOT_PARAM.getErrorCode());
            }
            Map<String, String> params = new HashMap<>();
            params.put("visitorId", visitorId);
            params.put("createTime", createTime);
            if (!Md5EncryptUtil.checkAppSignValue(params, sign, MINI_PROGRAM_REQUEST_PARAMS_ENCRYPT_KEY)) {
                return new MessageVO(AppErrorCodeEnum.APP_SIGN_ERR.getErrorCode());
            }
            MiniProgramVisitorInfoVO miniProgramVisitorInfoVO = iPropertyVisitorServiceClient.getQRCodeContent(visitorId);
            if (miniProgramVisitorInfoVO == null){
                return new MessageVO(MiniProgramErrorCodeEnum.QR_CODE_PASS_TIME_OR_NOT_EXISTS_ERR.getErrorCode());
            }
            return new MessageVO(BaseErrorCodeEnum.SUCCESS.getErrorCode(), miniProgramVisitorInfoVO);
        }catch (Exception e){
            throw new DataAccessException("【小程序_getQRCodeContent】获取访客二维码内容失败", e);
        }
    }

}
